When you are creating a new entry in your linked list, you are attempting to append it to the list by starting at the head and iterating the list until you find a NULL
in evCurrent->next
. When you do find a NULL
you stop iterating the list and, at that point, assign newEvent
as the next entry in the list via evCurrent->next = newEvent;
— and, of course, if there are no entries in the linked list, you make the new entry the head of the list via listEvents->firstEvent = newEvent;
However, at no time do you initialize the value of newEvent->next
. Note that malloc()
does not initialize the block of memory it returns. It simply allocates a block and returns it to you. See the docs here http://www.cplusplus.com/reference/cstdlib/malloc/
The key bit is this...
The content of the newly allocated block of memory is not initialized, remaining with indeterminate values.
Therefore, newEvent->next
is, for all practical purposes, a random value. Thus, your code is off into random memory walks because you are counting on it being NULL
to terminate the linked list.
I might suggest you try calloc()
instead.
Evenement *newEvent = calloc( 1, sizeof(*nvEvent) );
Otherwise, ensure that the value of the next
element is initialized to NULL
when you create it.