Search code examples
clinked-listfree

How to check if free(node) works


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...

  1. Does this method work?
  2. Do I need to malloc tempNode?
  3. I initialized tempNode before while loop... but after I free, tempNode still works... I don't really get that part

The theory that I used:

  1. # of free() == # of malloc()
  2. You need a temporary node to hold the current node
  3. Let the current node equal to the next node
  4. Free the current node by using the temporary node

If any of my theory sounds wrong, please explain!

Thanks!


Solution

  • The method certainly works - but it should be mallocd first before freeing. 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