Memory cleanup for linked lists
What you'll learn: How to safely traverse and deallocate every node in a linked list to prevent memory leaks.
The "Bridge Burning" Problem
In C, every time you use malloc() to create a node, you are responsible for using free() to give that memory back to the system. With a single variable, this is easy. With a linked list, it is a bit like walking across a series of floating platforms that are connected by ropes.
If you stand on the first platform and destroy it while you are still standing there, you fall into the water. If you destroy the platform before looking at where the rope leads, you lose the connection to the rest of the chain forever. This is a memory leak, and in a long-running program, it can eventually crash your computer.
The Two-Pointer Technique
To safely clean up a list, you cannot just use one pointer. You need two: one to hold onto the current node you are deleting, and one to "reach ahead" and grab the address of the next node before the current one vanishes.
Think of it like a relay race where you must hand off the baton (the address of the next node) before the current runner leaves the track.
Implementation in C
Here is how you write a function to clear an entire list. We start at the head and move forward until we hit NULL.
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void freeList(struct Node* head) {
struct Node* current = head;
struct Node* nextNode;
while (current != NULL) {
// 1. Save the pointer to the next node
nextNode = current->next;
// 2. Now it is safe to free the current node
free(current);
// 3. Move 'current' to the next node we saved
current = nextNode;
}
}
Why the order matters
If we called free(current) before assigning nextNode = current->next, we would be attempting to access current->next from memory that we no longer own. This results in "undefined behavior," which is a fancy way of saying your program might crash or act unpredictably. By saving the "next" step first, we ensure we always have a map to the rest of the list.
Key takeaway
To delete a linked list, always store the address of the next node in a temporary pointer before freeing the current node.