Memory leaks
- C course
- Intermediate
- Lesson 9/116
- 5 min
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.
Practice 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);.
Starter code
#include <stdio.h>
#include <stdlib.h>
// Allocate three elements
// Assign 10, 20, 30
// Sum with a loop, print and free
int main(void) {
return 0;
}Sample 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;
}Expected output
60
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What's missing to prevent the leak?
int *arr = malloc(5 * sizeof(int));
arr[0] = 10;
printf("%d\n", arr[0]);
____(arr);
int *arr = malloc(5 * sizeof(int));
arr[0] = 10;
printf("%d\n", arr[0]);
free(arr);
Explanation: free(arr) returns the memory; it prevents the leak.
2 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 Correct answer
Explanation: Losing the address returned by malloc.
3 Match leak and safe patterns
| Term | Meaning |
|---|---|
malloc without free |
Causes leak |
free(arr) call |
Safe pattern |
arr = NULL before free |
Address loss |
valgrind tool |
Leak finder |