0x1337
0x1337

Reputation: 1114

Weird segmentation fault 11

There are two files:

Matrix.hpp:

template <typename T>
class Matrix {
private:
    size_t rows = 0;
    size_t cols = 0;
    T* data = nullptr;
public:
    Matrix() = default;
    ~Matrix();
    Matrix(size_t n, size_t m);
    T& operator() (size_t i, size_t j);
};

template <typename T>
Matrix<T>::Matrix(size_t n, size_t m) : rows(n), cols(m) {
    try {
        data = new T[rows*cols];
    } catch (const std::bad_alloc& e) {
        std::exit(EXIT_FAILURE);
    }
};

template <typename T>
Matrix<T>::~Matrix() {
    delete[] data;
}

template <typename T>
T& Matrix<T>::operator()(size_t i, size_t j) {
    if (i < rows && i >= 0 && j < cols && j >= 0) {
        return data[(i+1)*cols + (j+1)];
    } else {
        throw std::logic_error("matrix indices out of range");
    }
}

and

Main.cpp:

#include <iostream>
#include "Matrix.hpp"

int main() {
    size_t n, k;
    std::cin >> n >> k;
    Matrix<long double> m = {n, k};
    for (size_t i = 0; i < m.getNumRows(); ++i) {
        for (size_t j = 0; j < m.getNumCols(); ++j) {
            std::cin >> m(i,j);
        }
    }

    for (size_t i = 0; i < m.getNumRows(); ++i) {
        std::cout << "\n";
        for (size_t j = 0; j < m.getNumCols(); ++j) {
            std::cout << m(i, j) << " ";
        }
    }
    return 0;
}

When I'm entering something like:

1 2 3 4

I can get

3 4

as answer but sometimes the same input causes Segmentation fault 11 moreover when I'm changing template argument from long double to int, error disappears. How can I fix it?

Upvotes: 2

Views: 137

Answers (1)

Simon Kraemer
Simon Kraemer

Reputation: 5690

Your operator function is accessing data outside its bounds. Passing (0,0) to the function should return data[0]. Currently it returns data[2]. Change line

return data[(i+1)*cols+(j+1)];

to

return data[i*cols+j];

Upvotes: 4

Related Questions