I am using a doubly linked list in a C program. I am getting confused about freeing the memory.
- Should I free the list node by node?
- Or, by assigning head and tail nodes to NULL?
I am using a doubly linked list in a C program. I am getting confused about freeing the memory.
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.
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.
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;
}