Why does accessing a member of a malloced array of structs seg fault?

Posted by WSkinner on Stack Overflow See other posts from Stack Overflow or by WSkinner
Published on 2012-04-05T17:22:03Z Indexed on 2012/04/05 17:30 UTC
Read the original article Hit count: 199

I am working through Learn C The Hard Way and am stumped on something. I've written a simplified version of the problem I am running into to make it easier to get down to it. Here is the code:

#include <stdlib.h>

#define GROUP_SIZE 10
#define DATA_SIZE 64

struct Dummy {
    char *name;
};

struct Group {
    struct Dummy **dummies;
};

int main() {
    struct Group *group1 = malloc(sizeof(struct Group));
    group1->dummies = malloc(sizeof(struct Dummy) * GROUP_SIZE);
    struct Dummy *dummy1 = group1->dummies[3];

    // Why does this seg fault?
    dummy1->name = (char *) malloc(DATA_SIZE);

    return 0;
}

when I try to set the name pointer on one of my dummies I get a seg fault. Using valgrind it tells me this is uninitialized space. Why is this?

© Stack Overflow or respective owner

Related posts about c

    Related posts about memory