C
Memory leaks
Learn the memory leak concept and how to prevent it.
What is a memory leak?
A memory leak happens when allocated memory becomes unreachable without being freed. The pointer is lost but the memory stays allocated.
Example: int *arr = malloc(100 * sizeof(int)); arr = NULL;. When arr is set to NULL the original address is lost; but the 100-int block is still allocated and can no longer be free'd. In long-running programs leaks accumulate and memory runs out. So every malloc needs a matching free; free before losing the address.
Preventing leaks
The golden rule to prevent leaks: every malloc needs a matching free. Free before losing the address. In complex functions, consider every return path.
For example, if a function returns early after a malloc, you must call free before returning. Tools like valgrind find leaks automatically; they report after the program runs. Be especially careful with early returns; before writing if (error) return;, free the allocated memory.
Exercise Sum and print without a leak
Allocate a three-element array with int *arr = malloc(3 * sizeof(int));. Assign 10, 20, 30 to the elements. Accumulate the sum in an int sum variable (using a for loop). Print it with printf("%d\n", sum). Free the memory with free(arr);.
Show example solution
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *arr = malloc(3 * sizeof(int));
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
int sum = 0;
for (int i = 0; i < 3; i++) sum += arr[i];
printf("%d\n", sum);
free(arr);
return 0;
}
Test yourself
-
What's missing to prevent the leak?
int *arr = malloc(5 * sizeof(int));
arr[0] = 10;
printf("%d\n", arr[0]);
____(arr);
Show answer
int *arr = malloc(5 * sizeof(int));
arr[0] = 10;
printf("%d\n", arr[0]);
free(arr);
-
Which situation causes a memory leak?
- Using arr after free(arr)
- Growing an array with realloc
- Freeing a NULL pointer
- Losing the address returned by malloc
Show answer
Losing the address returned by malloc — Losing the address returned by malloc.
-
Match leak and safe patterns
- malloc without free
- Causes leak
- free(arr) call
- Safe pattern
- arr = NULL before free
- Address loss
- valgrind tool
- Leak finder
Next lesson: Dangling pointers