Sub topic 13
Memory Leaks, Dangling Pointers, and Undefined Behavior
Assume you know basic C syntax, functions, arrays, and pointers. This chapter focuses on what can go wrong when pointers refer to dynamically allocated memory, then applies the rules to singly linked lists.
Memory leaks
A memory leak occurs when a program allocates heap memory but loses every pointer that refers to it. The memory remains allocated until the program ends, even though the program cannot use it.
int *p = malloc(5 * sizeof *p);
if (p != NULL) {
p[0] = 10;
}
p = NULL; // The allocated block can no longer be reached.The assignment to NULL does not release the block. The correct order is to call free first:
free(p);
p = NULL;Setting the pointer to NULL afterward prevents accidental reuse of the old address. Calling free(NULL) is safe, so cleanup code can use this pattern.
realloc can also cause problems. It may move a block, and it returns NULL if resizing fails. Use a temporary pointer so that a failed resize does not lose the original block:
int *temporary = realloc(p, 10 * sizeof *p);
if (temporary != NULL) {
p = temporary;
}| Problem | What happens | Prevention |
|---|---|---|
| Memory leak | Allocated memory becomes unreachable | Free each successful allocation |
| Double free | A block is released twice | Set pointers to `NULL` after freeing |
| Dangling pointer | A pointer refers to released memory | Do not dereference it after `free` |
| Out-of-bounds access | Code reads or writes outside an object | Check valid indices and sizes |
Structs and singly linked lists
A struct groups related fields. A singly linked list stores each value in a node that also points to the next node. The final node points to NULL.
The following program adds nodes at the front, traverses the list, and releases every node. Saving next before calling free is essential because the node's contents must not be read after it is released.
#include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node *next;
};
struct node *push(struct node *head, int value) {
struct node *new_node = malloc(sizeof *new_node);
if (new_node == NULL) {
return head;
}
new_node->value = value;
new_node->next = head;
return new_node;
}
void print_list(const struct node *head) {
for (const struct node *p = head; p != NULL; p = p->next) {
printf("%d ", p->value);
}
putchar('\n');
}
void free_list(struct node *head) {
while (head != NULL) {
struct node *next = head->next;
free(head);
head = next;
}
}
int main(void) {
struct node *head = NULL;
head = push(head, 30);
head = push(head, 20);
head = push(head, 10);
print_list(head);
free_list(head);
return 0;
}Exercise
After free(p), why is p = NULL useful, even though it does not restore the allocated memory?
Show answer
p becomes a known invalid pointer value, so later code is less likely to dereference the released block or free it again. The memory is released by free, not by assigning NULL.