Reputation: 467
I am getting a segmentation fault whenever I try to print the value stored within a struct. Using Valgrind, I was able to narrow it down a bit to one block of code, but I am unsure what I am doing wrong. Am I initializing my struct incorrectly?
Whenever I run valgrind, it tells me that there is an invalid write of size 8 where I say newList->data = d.
typedef struct List {
struct List *np[Ends]; // next/prev neighbors
Data data;
} *List;
typedef void *Data;
static void put(Data d) {
List newList = malloc(sizeof(List));
newList->data = d;
}
Upvotes: 1
Views: 277
Reputation: 223757
This is an example of why it's bad practice to typedef
a pointer.
Because List
is defined as an alias for struct List *
, sizeof(List)
gives you the size of a pointer, not the size of the struct. As a result, you're not allocating enough memory.
You instead want either malloc(sizeof(struct List))
or (preferably) malloc(sizeof *newlist)
Upvotes: 4