Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault error occurs for a simple function I have coded [closed]

Tags:

c++

Here I just want to define a function which returns the multiplication of matrices, with N arbitrary, I would like to generate a matrix with a new command. When I execute the function I get the error:

Segmentation fault (core dumped)

Whenever I assign values to C I have this error, could anybody tell me what happened and how to fix it?

int **multiply(int **A, int **B, int N){
    int **C = new int*[N];
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            for (int k = 0; k < N; k++)
                C[i][j] = C[i][j] + A[i][k] * B[k][j];
        }
    }
    return (C);
}
like image 355
user3622064 Avatar asked Jan 17 '26 10:01

user3622064


2 Answers

It is not a good idea to make matrices as pointers of pointers. To do that properly, you need a rather complex:

int **C = new int*[N];
for(int i = 0; i < N; ++ i)
    C[i] = new int[M];

And freeing this up is a similarly complicated process. Also think about what happens if one of the operator new fails and you want to free up the partially allocated matrix.

It is a convention to store 2D arrays inside of a 1D ones. You can do:

int *C = new int[M * N];

And then the elements are accessed as:

C_ij = C[i + N * j];

or as:

C_ij = C[j + M * i];

Where i is in [0, N) interval and j is in [0 to M) interval. These are actually quite similar to how the compiler generates accesses to a constant-sized 2D array (so the multiplication is in fact not overly costly, and when considering cache, the whole thing is likely to be much faster than your array of arrays). The difference between the two lines above is that the one is column-major (the elements of a column are consecutive items when unrolled to 1D) or alternately row-major. That is a matter of convention. The default "C" arrays will be row-major. Some libraries, such as OpenGL or Eigen use column major.

like image 65
the swine Avatar answered Jan 20 '26 02:01

the swine


int **C=new int*[N];

This makes space for an array of pointers. It doesn't initialize them, so they could point anywhere. They might even be NULL pointers.

C[i][j]

This might cause a null pointer dereference. That's probably what causes the segmentation fault.

like image 39
guest Avatar answered Jan 20 '26 00:01

guest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!