Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

malloc causing a SIGSEGV:Segmentation fault

Tags:

c

malloc

typedef struct Matrix
{
    double * matrix;
    int sizex;
    int sizey;
}Matrix;

int nn = 257;
Matrix * g = (Matrix *)malloc(sizeof(Matrix *));
g->matrix = malloc(sizeof(double) * nn * nn);
g->sizex = nn;
g->sizey = nn;

This code give an error when it gets to g->matrix = malloc(sizeof(double) * nn * nn); anyone see a problem with it ?

edit: found problem to be accessing unallocated memory in a place before the allocation shown, it was causing a SIGSEGV:Segmentation fault.

like image 447
Abraham Adam Avatar asked Jan 01 '26 01:01

Abraham Adam


1 Answers

You need to pass malloc the sizeof the Matrix not sizeof pointer to the Matrix.

Change

Matrix * g = (Matrix *)malloc(sizeof(Matrix *));
                                           ^^ 

to

Matrix * g = (Matrix *)malloc(sizeof(Matrix));

Also you must always check the return value of malloc and make sure allocation succeed before you go and use the allocated memory.

like image 101
codaddict Avatar answered Jan 02 '26 13:01

codaddict



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!