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:
#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?
Your use of
dummiesappears inconsistent with its declaration. From the way you use thedummiesfield it appears thatdummieswas intended as an array ofDummystructs, not an array of arrays ofDummystructs. If this is the case, change your declaration to this:Then change your usage as follows:
Of course this assumes that
GROUP_SIZEis four or more.