Losing the head pointer causes a memory leak

You are given a linked list with five nodes and only have access to the first node, like this:

Node *head = createNode(1);
insertNode(head, 2);
insertNode(head, 3);
insertNode(head, 4);
insertNode(head, 5);

Using head, you can traverse the entire list:

printAll(head); // 1 -> 2 -> 3 -> 4 -> 5

What happens if you accidentally assign NULL to head?

head = NULL;
printAll(head) // < blank output >

Now, you’ve lost access to all the other four nodes. Since no pointer refers to them anymore, they cannot be freed. They will remain allocated in memory until the program terminates, causing a memory leak.

Backlinks: