tags:

views:

106

answers:

3

I am using a doubly linked list in a C program. I am getting confused about freeing the memory.

  1. Should I free the list node by node?
  2. Or, by assigning head and tail nodes to NULL?
+4  A: 

You have to free each node. If you just set the head and tail nodes to NULL, you will leak all of the memory allocated for the list.

Donnie DeBoer
+7  A: 

You have to traverse the list and free each node. If you only set the head and tail pointers to NULL the list nodes are still in the heap and you have no pointers to them and that's a classic memory leak.

Here's some pseudocode:

Node* current = head;
while( current != NULL ) {
   Node* next = current->Next;
   free( current );
   current = next;
}
// done

You could of course traverse for tail to head - doesn't make any major difference.

sharptooth
+7  A: 

If they were dynamically allocated, you need to free the nodes. Keep in mind that if your nodes hold pointers to some data, and that data was also dynamically allocated, you'll need to free that too.

Something like:

list_node* node = head;
while (node)
{
    /* depends */
    /* free(node->data); */

    list_node* next = node->next;
    free(node);
    node = next;
}
GMan