Question

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?

Was it helpful?

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.

OTHER TIPS

You're currently passing a copy of M to allocMatrix. The memory you allocate here is leaked when the function returns. You need to pass a pointer to M if you want the caller's variable to be modified

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

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

Since you are writing C++, why not use vector?

#include <vector>

int main()
{
    // This does what your "allocMatrix" does.
    std::vector< std::vector<double> > M(numberOfLines, numberOfColumns);

    // Look Ma!  No need for a "freeMatrix"!
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top