Malloc calls SIGSEGV: segmentation error

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 gives an error when it gets into g->matrix = malloc(sizeof(double) * nn * nn); anyone sees a problem with it?

edit: found that the problem is access to unallocated memory in place before the allocation shown, this caused an error SIGSEGV: Segmentation.

+3
source share
7 answers

You need to pass the mallocsize Matrixnot sizeof the pointer to Matrix.

Edit

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

to

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

Also, you should always check the return value mallocand make sure that the allocation is successful before you go and use the allocated memory.

+6
source

, - 16- , , Turbo C. Junk it gcc, djgpp, DOS- mingw cygwin, Windows.

, , 257 * 257 , 65536, , , 8.

: , , . , .

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

, . :

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

:

#include <stdlib.h>
#include <stdio.h>

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

int main()
{
    int nn = 257;
    Matrix * g = (Matrix *)malloc(sizeof(Matrix));
    if (g == NULL)
    {
        printf("g = malloc() failed\n");
        return 1;
    }
    g->matrix = malloc(sizeof(double) * nn * nn);
    g->sizex = nn;
    g->sizey = nn; 
    printf("g %p, g->matrix %p, g->sizex %d, g->sizey %d\n",
            g, g->matrix, g->sizex, g->sizey);
    return 0;
}

Linux:

g 0x8822008, g->matrix 0xf6ea6008, g->sizex 257, g->sizey 257
0
Matrix * g = (Matrix *)malloc(sizeof(Matrix *));

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

, .

0

Matrix, .

malloc, :

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

, - void * C, sizeof , . , g ( ).

:

g->matrix = malloc(sizeof(double) * nn * nn);

:

g->matrix = malloc(sizeof(*(g->matrix)) * nn * nn);

0

sizeof .

0
0

Source: https://habr.com/ru/post/1780826/


All Articles