C Deallocate Memory
Asking for memory is only half of the story. In this lesson you will learn how to deallocate, or free, memory with the free() function, which is essential for writing programs that do not waste resources.
When you allocate memory with malloc() or calloc(), that memory stays reserved for your program until you explicitly give it back. Handing it back is called deallocating or freeing the memory, and it is done with the free() function. This returns the space to the system so other parts of your program, or other programs, can use it.
Freeing Memory with free()
The free() function is simple: you pass it the same pointer that malloc() or calloc() gave you, and the memory is released. You should call free() exactly once for each block you allocated, no more and no less.
Allocate, use, then free
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = malloc(sizeof(int));
if (ptr == NULL) {
return 1;
}
*ptr = 100;
printf("Stored value: %d\n", *ptr);
// Return the memory to the system
free(ptr);
ptr = NULL; // avoid using it by accident later
return 0;
}Notice that after calling free(ptr), we set ptr to NULL. After freeing, the pointer still holds the old address, but that memory no longer belongs to us. Setting it to NULL marks it as empty, so if we accidentally use it again, the program fails clearly instead of behaving in unpredictable ways.
Common Memory Mistakes to Avoid
- Memory leak: forgetting to call free(), so the memory is never returned.
- Double free: calling free() twice on the same pointer, which corrupts memory.
- Dangling pointer: using a pointer after its memory was freed.
- Freeing the wrong pointer: calling free() on memory that was not allocated with malloc or calloc.
Free an allocated array
#include <stdio.h>
#include <stdlib.h>
int main() {
int *list = malloc(3 * sizeof(int));
if (list == NULL) {
return 1;
}
list[0] = 1;
list[1] = 2;
list[2] = 3;
// One free() releases the whole block
free(list);
list = NULL;
printf("Memory has been released.\n");
return 0;
}