Graph memory management
What you'll learn: How to properly allocate and free memory for a graph to prevent memory leaks in long-running programs.
Graphs are "nested" structures. Unlike a simple array, a graph (especially one using an Adjacency List) consists of a pointer to an array, which contains pointers to linked lists, which contain individual nodes. Because of this layering, you cannot simply call free(graph) and expect everything to disappear. If you do, you leave the "branches" of your graph floating in memory, creating a leak.
The "Cleanup" Rule
Think of a graph like a physical filing cabinet. Each drawer represents a vertex, and inside each drawer is a chain of paperclips representing edges. If you throw away the cabinet frame without emptying the drawers, the paperclips are still scattered on the floor.
To manage memory correctly in C, you must reverse the order of creation:
- Iterate through every vertex.
- For each vertex, traverse its linked list and
freeevery edge node. - Once the edges are gone,
freethe array that held the list heads. - Finally,
freethe graph structure itself.
Implementation in C
Here is how you safely dismantle an adjacency list graph:
#include <stdlib.h>
struct Node {
int target;
struct Node* next;
};
struct Graph {
int numVertices;
struct Node** adjLists; // Array of pointers
};
void destroyGraph(struct Graph* graph) {
if (graph == NULL) return;
// 1. Free every node in every adjacency list
for (int i = 0; i < graph->numVertices; i++) {
struct Node* temp = graph->adjLists[i];
while (temp != NULL) {
struct Node* toDelete = temp;
temp = temp->next;
free(toDelete);
}
}
// 2. Free the array of pointers
free(graph->adjLists);
// 3. Free the graph container itself
free(graph);
}
Why this matters
In data structures like graphs, memory leaks accumulate quickly. Because a single vertex might connect to thousands of edges, failing to free those edges can crash your system in minutes. Always ensure that every malloc used during your addEdge or createGraph functions has a corresponding free in your cleanup logic.
Key takeaway
Free a graph from the "inside out"—delete the edge nodes first, then the adjacency array, and finally the graph structure itself.