0

I have problem with this code:

1) Segmentation fault in cpp object.

The same code working on main function.

// Create
vector< vector<int> > vec(4, vector<int>(4));
// Write
vec[2][3] = 10;
// Read
int a = vec[2][3];

I create a two-dimensional array element. There is a problem with memory allocation. I do not know how to handle it.

#include <iostream>
#include <vector>    
using namespace std;

class Matrix
{
public:
    int m, n;
    Matrix();
    Matrix(int, int);
    vector<vector<int> > vec;
};

int main()
{
    Matrix obj(3, 4);
    obj.vec[1][2] = 33;
    return 0;
}

Matrix::Matrix()
{
    n = 0;
    m = 0;
    vector< vector<int> > vec(m, vector<int>(n));
}

Matrix::Matrix(int m, int n)
{
    this->m = m;
    this->n = n;
    vector< vector<int> > vec(m, vector<int>(n));
}
JeJo
  • 30,635
  • 6
  • 49
  • 88
Mouse
  • 23
  • 3

1 Answers1

3

You have not allocated the vec member of the Matrix class, rather you have introduced a local std::vector<std::vector<int>> vec in the Matrix's constructor, which has only the lifetime inside the constructor.

You should be std::vector::resize ing the member vec using the m and n passed.

Matrix::Matrix(int m, int n)
{
    this->m = m;
    this->n = n;
    vec.resize(m, std::vector<int>(n));
}

or use constructor member initializer lists to initlize the vec.

Matrix::Matrix(int m, int n)
    : m{ m }
    , n{ n }
    , vec(m, std::vector<int>(n))
{}

As a side note:

  • Use a different name for the members and the constructor parameters, to avoid confusions.

  • Do not practice withusing namespace std;.

For example:

#include <vector>

class Matrix /* final */
{
    int mRow, mCol;
    std::vector<std::vector<int>> mStorage;

public:    
    Matrix(int m, int n)  // different name as the members
        : mRow{ m }
        , mCol{ n }
        , mStorage(mRow, std::vector<int>(mCol))
    {}
};
JeJo
  • 30,635
  • 6
  • 49
  • 88
  • I have problem with constructor without parameters. Segmentation fault. @JeJo ' Matrix::Matrix() { n=0; m=0; vec.resize(m, vector(n)); }' – Mouse Dec 29 '19 at 19:32
  • @Mouse There you also have the same problem as the other constructor, but that does not affect the program. Since m and n are `0` the size of the `vec` also will be `0`, therefore accessing elements via `std::vector::operator[]` is out of bound **[undefined behaviour](https://en.cppreference.com/w/c/language/behavior#Access_out_of_bounds)** Therefore, you shouldn't be doing it! – JeJo Dec 29 '19 at 19:39