Here is the code for freeing the whole linked list
void free_list(RecordType *list)
{
RecordType *tempNode; /* temporary Node to hold on the value of previous node */
while(list != NULL) /* as long as the listnode doesn't point to null */
{
tempNode = list; /* let tempNode be listNode in order to free the node */
list = list->next; /* let list be the next list (iteration) */
free(tempNode); /* free the node! */
}
}
I think this code itself is working ok (?), but I have no idea how to check. I only applied the theory (e.g. # of frees must = to the # of mallocs)
So here are some questions that I'm wondering...
The theory that I used:
If any of my theory sounds wrong, please explain!
Thanks!
The method certainly works - but it should be malloc
d first before free
ing. Otherwise it is undefined behavior.
You don't need to malloc()
tempNode
only if list
has been previously malloc()
d.
The third part is undefined behavior. After free()
the data may still exist, but is flagged for being overwritten. You cannot rely on the node once it is free()
d