I need to write a LinkedList in C,
I defined the construct in the file as struct element { int value; struct element * next; };
I also defined a head element.
Both of these are not local, they are variables that persist throughout runtime.
When I try to insert elements into the LinkedList using int-values from outside, I need to wrap an element around this int. I do this by creating a local variable struct element e = { value; 0 };. I make it the head if head is null, or else I append it using a for-loop.
The problem I figured is that the local variable e of type struct element is deleted upon terminating that function. So if I have my head point to e, it will continue pointing to an unallocated point of memory since the local variable e does not persist beyond the function call.
Thanks in advance!
That is because
struct element e = { value; 0 };allocates the element on the stack. Stacks are automatically deallocated (deleted) when the function scope terminates. Addressing stack memory of an active scope is perfectly valid, but that of a scope that has terminated is undefined behavior.You need to allocate it on the heap via
malloc(sizeof(struct element));to make it persist through function scopes.Note:
callocallocates zeroed out memory,mallocallocates memory with undefined content.