简体   繁体   中英

Segmentation fault (core dumped) after adding an array inside a struct

I'm trying to add an array called shape inside a struct but once I add it and try to access the member values , it produces a segmentation fault. If I remove it, the program works perfectly.

This is the struct definition:

struct coo_matrix{
    int nnz;
    int shape[2];
    int * rows;
    int * columns;
    int * values;
};
typedef struct coo_matrix * COOMatrix;

This is the function where I try to access values :

COOMatrix coo_matrix_create(int m, int sparse_matrix[][m]){
    ...
    COOMatrix coo;
    coo = malloc(sizeof(COOMatrix));
    coo->rows = malloc(n * m * sizeof(int));
    coo->columns = malloc(n * m * sizeof(int));
    coo->values = malloc(n * m * sizeof(int));
    ....
    ....
            coo->rows[k] = i;
            coo->columns[k] = j;
            coo->values[k] = sparse_matrix[i][j]; // see Note
    ....
    return coo;
}

Note : Once I add shape, this line produces a segmentation fault.

PS: No need to say I am not very familiar with C, I learned other languages before I ever touched C recently.

You have a couple of problems in that code. First, you declare your COOMatrix as a pointer but then confuse things by using it to get the size of the underlying struct. Secondly, you declare rows, columns and values as pointers to ints but then allocate them using sizeof(COOMatrix). Because of the first error, the second might actually work depending on the machine but isn't what you want. So

struct coo_matrix{
...
};
typedef struct coo_matrix COOMatrix;
COOMatrix *coo_matrix_create(int m, int sparse_matrix[][m]){
    ...
    COOMatrix *coo;
    coo = malloc(sizeof(COOMatrix));
    coo->rows = malloc(n * m * sizeof(int));
    coo->columns = malloc(n * m * sizeof(int));
    coo->values = malloc(n * m * sizeof(int));
    ....
    ....
            coo->rows[k] = i;
            coo->columns[k] = j;
            coo->values[k] = sparse_matrix[i][j]; // see Note
    ....
    return coo;
}

Should be closer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM