Search code examples
cmallocdynamic-arrays

Segfault while accessing dynamicly allocated C struct array


I have the following struct that is defined in the following way

typedef struct _abcd {
    int a;
    unsigned long b;  
    void (*c)(int);
    int d;
} abcd_t, *abcd;

Now i have the following code

static abcd foo

int set_size(int size){
   foo = malloc(sizeof(abcd) * size);
}

This code for some reason gives me segfault when accessing some of the properties of array members. But i have noticed that if i change the malloc line to the following - it fixes the issue

foo = malloc(sizeof(foo[0]) * size);

I find it strange as obviously sizeof(foo[0]) = sizeof(abcd) So what is exactly the difference here?

Thanks


Solution

  • obviously sizeof(foo[0]) = sizeof(abcd)

    It is not the same since you typedefed abcd to be a *pointer* to struct _abcd.

    Use

    foo = malloc(sizeof(*foo) * size);
    

    to have robust code even if the type of foo should change at some point.

    Your

    foo = malloc(sizeof(foo[0]) * size);
    

    is essentially the same since foo[0] is just syntactic sugar for *(foo + 0) which becomes *foo.