Search code examples
c++matrixsegmentation-faultdynamic-allocation

Segmentation fault (core dumped) on Ubuntu with matrix functions on C++


I'm trying to build a program in C++ that works a lot with matrices and functions of matrices. My code compiles normally, but when I try to execute it I get the message:

Segmentation fault (core dumped)

My code has a lot of function that look like this:

void function(double **matrix, ...) {
    //Operations with the matrix
}

And I call the functions like this:

double **M;
function(M,...);

By researching about the message I discovered that I needed to dynamically allocate the matrices that I was going to use, so wrote the following functions that should do this allocation:

void allocMatrix(double **M, int nl, int nc) {
M = new double*[nl];
for(int i = 0; i < nl; ++i)
        M[i] = new double[nc];
}

void freeMatrix(double **M, int nl) {
for(int i = 0; i < nl; ++i)
         delete [] M[i];
delete [] M;
}

Now with these functions I tried to call my other functions doing the following:

double **M;
allocMatrix(M, numberOfLines, numberOfColumns);
function(M,...);
freeMatrix(M, numberOfLines);

However, even with this change I keep getting the message "Segmentation fault (core dumped)".

I even tried to allocate the matrix inside the functions like this:

void function(double **matrix, ...) {
    allocMatrix(M, numberOfLines, numberOfColumns);
    //Operations with the matrix
    freeMatrix(M, numberOfLines);
}

But it didn't work as well.

Does anyone know where I'm not getting it right?


Solution

  • You need to pass double *** in the parameter list and send &M (the address of M) in the call. Without that, your M does not have the matrix and you get the seg fault in a different function.