Cleaning up heap memory before exit
What you'll learn: How to properly release dynamically allocated memory to ensure Valgrind reports a perfectly clean bill of health.
The "Borrow and Return" Rule
In C, the heap is like a library. When you use malloc(), you are checking out a book. The operating system is a patient librarian; it will eventually get its books back when your program ends, but tools like Valgrind are much stricter. They want to see that you, the programmer, explicitly returned every single book before you walked out the door.
If you allocate memory and let the program end without calling free(), Valgrind will flag this as "definitely lost" or "still reachable" memory. While your computer won't explode, these leaks in larger programs can lead to system slowdowns and crashes.
Closing the Loop
To satisfy memory debuggers, every malloc() must have a matching free(). A good habit is to write your cleanup code the moment you write your allocation code. If you open a door, plan how to close it.
Here is a simple example of a program that allocates space for an integer array and cleans up correctly:
#include <stdio.h>
#include <stdlib.h>
int main() {
int size = 5;
// 1. Allocate memory (The "Borrow")
int *arr = malloc(size * sizeof(int));
if (arr == NULL) {
return 1; // Always check if allocation failed
}
// Use the memory
for (int i = 0; i < size; i++) {
arr[i] = i * 10;
printf("%d ", arr[i]);
}
// 2. Deallocate memory (The "Return")
free(arr);
// 3. Prevent accidental use (Optional but safe)
arr = NULL;
return 0;
}
Why Valgrind Cares
When you run this through Valgrind with the command valgrind --leak-check=full ./my_program, the tool tracks the address returned by malloc(). If that address isn't passed to free() before main() returns, Valgrind notes it down.
By explicitly freeing memory, you prove to the debugger (and yourself) that you have full control over your program's resources. A "clean" Valgrind report—showing 0 bytes lost—is the gold standard for professional C code. It means your program is efficient and respects the system's shared memory.
Key takeaway
Every block of memory you request with malloc() must be explicitly released with free() before your program finishes to ensure a leak-free execution.