Search code examples
cstructsegmentation-faultdynamic-memory-allocation

Segmentation fault (core dumped) in dynamic memory allocation using a pointer(member) from struct


I am using the following code and in line "arr[0]->p = (int *)malloc(m * sizeof(int));"I have "Segmentation fault (core dumped)". I need to write my code in this way...

Can someone help how can I write this and why my code have this error?

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

typedef struct data{
    int *p;
}data;

void main(){
    int n = 10, 
        m = 5 ;
        
    data **arr = (data**)malloc(n * sizeof(struct data*));
    arr[0]->p = (int *)malloc(m * sizeof(int));

}

something like this it works

    /************************************************************
    *                                                           *
    *      data *arr = (data*)malloc(sizeof(struct data));      *
    *      arr->p = (int *)malloc(m * sizeof(int));             *
    *                                                           *
    *************************************************************/

Solution

  • You don't need an array of pointers. Allocate an array of structs and then allocate memory for the p member of the structs.

    data *arr = malloc(n * sizeof(data));
    for (int i = 0; i < n; i++) {
        arr[i].p = malloc(m * sizeof(int));
    }
    

    If you really do need an array of pointers, you need to allocate memory for the struct that each pointer points to.

    data **arr = malloc(n * sizeof(data*));
    for (int i = 0; i < n; i++) {
        arr[i] = malloc(sizeof(struct data));
        arr[i]->p = malloc(m * sizeof(int));
    }