- How to model a graph with an adjacency list using dynamic memory
- How to allocate nodes with
malloc()and check forNULL - How to add edges to an undirected graph (both directions)
- How to traverse and print the graph
- How to free the graph in the correct order — nodes → array → struct
Purpose & Objective
To expand a C program that dynamically allocates memory for a graph structure and implements functions to add vertices and edges, we will cover every step systematically. This program illustrates the essential operations of graph manipulation using dynamic memory allocation in C, explains real-life applications, and presents a detailed code explanation with output.
Purpose:
- Understanding Graph Data Structures: Implementing a graph using dynamic memory allocation builds an understanding of vertices and edges — fundamental to representing relationships between entities.
- Dynamic Memory Allocation: Learn how to allocate memory dynamically for graph nodes and edges to accommodate varying graph sizes and structures at runtime.
💡 Quick Definition: A graph is a set of vertices (nodes) connected by edges. In an undirected graph, an edge from A to B is the same as one from B to A — that's why we add two entries per edge in an adjacency list.
What is a Graph?
A graph is a data structure consisting of:
- Vertices (V): The individual entities — cities, users, network devices, or any object.
- Edges (E): The connections between vertices — roads, friendships, links.
Graphs can be directed (edge has a direction) or undirected (edge is bidirectional). They can be weighted (each edge has a cost) or unweighted. This program builds an unweighted, undirected graph.
Adjacency List vs Adjacency Matrix
There are two common ways to store a graph. This program uses the adjacency list because it's memory-efficient for sparse graphs.
| Approach | Memory | Best for |
|---|---|---|
| Adjacency Matrix | O(V²) | Dense graphs where V is small |
| Adjacency List | O(V + E) | Sparse graphs, dynamic graphs |
Real-Life Applications
Graphs are used to model relationships in real-world systems. Here are common examples:
Social Networks
Users are vertices, and friendships are edges. Friend-of-a-friend suggestions are computed by graph traversal.
Transportation Networks
Cities are vertices, and roads are edges. Route planning, shortest paths, and traffic optimization are graph algorithms.
Computer Networks
Devices (routers, switches, hosts) are vertices, and physical or logical connections are edges. Routing tables are essentially graph lookups.
Complete C Program
Program: Dynamically allocate a graph and add vertices and edges
#include <stdio.h>
#include <stdlib.h>
/* Structure for an adjacency list node */
struct AdjListNode {
int dest;
struct AdjListNode* next;
};
/* Structure for adjacency list of each vertex */
struct AdjList {
struct AdjListNode *head;
};
/* Structure for a graph */
struct Graph {
int V; /* Number of vertices */
struct AdjList* array; /* Array of adjacency lists */
};
/* Function to create a new adjacency list node */
struct AdjListNode* newAdjListNode(int dest) {
struct AdjListNode* newNode = (struct AdjListNode*) malloc(sizeof(struct AdjListNode));
if (!newNode) {
printf("Memory allocation failed.\n");
exit(1);
}
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}
/* Function to create a graph of V vertices */
struct Graph* createGraph(int V) {
int i;
struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph));
if (!graph) {
printf("Memory allocation failed.\n");
exit(1);
}
graph->V = V;
graph->array = (struct AdjList*) malloc(V * sizeof(struct AdjList));
if (!graph->array) {
printf("Memory allocation failed.\n");
exit(1);
}
/* Initialize each adjacency list as empty */
for (i = 0; i < V; ++i)
graph->array[i].head = NULL;
return graph;
}
/* Function to add an edge to an undirected graph */
void addEdge(struct Graph* graph, int src, int dest) {
struct AdjListNode* newNode;
/* Add an edge from src to dest */
newNode = newAdjListNode(dest);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
/* Since the graph is undirected, add an edge from dest to src too */
newNode = newAdjListNode(src);
newNode->next = graph->array[dest].head;
graph->array[dest].head = newNode;
}
/* Function to print the graph */
void printGraph(struct Graph* graph) {
int v;
for (v = 0; v < graph->V; ++v) {
struct AdjListNode* temp = graph->array[v].head;
printf("Adjacency list of vertex %d\n", v);
while (temp) {
printf(" -> %d", temp->dest);
temp = temp->next;
}
printf("\n");
}
}
/* Function to free graph memory */
void freeGraph(struct Graph* graph) {
int v;
if (graph) {
if (graph->array) {
for (v = 0; v < graph->V; ++v) {
struct AdjListNode* temp = graph->array[v].head;
while (temp) {
struct AdjListNode* prev = temp;
temp = temp->next;
free(prev);
}
}
free(graph->array);
}
free(graph);
}
}
/* Main function to demonstrate graph operations */
int main() {
int V, E, i;
int src, dest;
struct Graph* graph;
printf("Enter the number of vertices in the graph: ");
scanf("%d", &V);
graph = createGraph(V);
printf("Enter the number of edges in the graph: ");
scanf("%d", &E);
printf("Enter the edges (src dest):\n");
for (i = 0; i < E; ++i) {
scanf("%d %d", &src, &dest);
addEdge(graph, src, dest);
}
printf("Graph created successfully!\n");
printf("Here is the adjacency list representation of the graph:\n");
printGraph(graph);
/* Free dynamically allocated memory */
freeGraph(graph);
return 0;
}
Program Output
Enter the number of vertices in the graph: 5
Enter the number of edges in the graph: 4
Enter the edges (src dest):
0 1
0 4
1 4
2 3
Graph created successfully!
Here is the adjacency list representation of the graph:
Adjacency list of vertex 0
-> 4 -> 1
Adjacency list of vertex 1
-> 4 -> 0
Adjacency list of vertex 2
-> 3
Adjacency list of vertex 3
-> 2
Adjacency list of vertex 4
-> 1 -> 0
Step-by-Step Explanation
Let's break down this program section by section:
1. Data structures:
struct AdjListNode { int dest; struct AdjListNode* next; };
struct AdjList { struct AdjListNode *head; };
struct Graph { int V; struct AdjList* array; };
AdjListNode is one entry in an adjacency list — a destination vertex plus a pointer to the next entry. AdjList wraps the head pointer for a single vertex. Graph holds the vertex count and an array of AdjList.
2. Create the graph:
graph = (struct Graph*) malloc(sizeof(struct Graph));
graph->array = (struct AdjList*) malloc(V * sizeof(struct AdjList));
for (i = 0; i < V; ++i)
graph->array[i].head = NULL;
Two allocations: the graph struct, then the array of adjacency lists. Every list starts empty (head = NULL).
3. Add an edge:
newNode = newAdjListNode(dest);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
/* repeat with src and dest swapped */
Because the graph is undirected, every edge is stored twice: once under src pointing to dest, and once under dest pointing to src. This makes lookups fast in both directions. Prepending at the head is O(1).
4. Print the graph:
for (v = 0; v < graph->V; ++v) {
printf("Adjacency list of vertex %d\n", v);
temp = graph->array[v].head;
while (temp) {
printf(" -> %d", temp->dest);
temp = temp->next;
}
}
For each vertex, walk its linked list and print every destination. Because we prepend, the order is reversed from insertion order — that's why vertex 0's list shows 4 -> 1 (4 was inserted last, so it's first in the list).
5. Free the graph:
for (v = 0; v < graph->V; ++v) {
while (temp) { prev = temp; temp = temp->next; free(prev); }
}
free(graph->array);
free(graph);
Order matters: first free every node in every adjacency list, then the array of lists, then the graph struct itself. Reversing the order would leave dangling pointers.
🎯 Key Takeaway: A graph as an adjacency list is really an array of linked lists. Once you see it that way — one linked list per vertex — every graph operation becomes a list traversal. That's why graphs feel less intimidating once you already know linked lists.
Frequently Asked Questions
1. Why does each edge get inserted twice?
Because this is an undirected graph — if A connects to B, then B connects to A. Storing both directions makes traversal from either side possible without special handling. For a directed graph, you'd add only one entry.
2. Why is the order reversed in the output?
Because addEdge prepends new nodes at the head of the list. If you insert edges in order 0-1, then 0-4, vertex 0's list ends up as 4 -> 1. If you want insertion order preserved, walk to the tail and append — but that costs O(degree) per edge instead of O(1).
3. Can I add vertices after creating the graph?
Not with this implementation — the array of adjacency lists is fixed-size. To add vertices, you'd need to realloc the array and initialize the new slot's head to NULL. That's a good follow-up exercise.
4. What's the memory footprint of this adjacency list?
O(V + E). The array holds V pointers, and each of the 2E edge nodes holds an int + a pointer. Compare to an adjacency matrix, which is O(V²) regardless of edge count — much heavier for sparse graphs.
💡 Tip: Compile with gcc -fsanitize=address -g to catch leaks and use-after-free bugs instantly — especially important with nested frees.