C Memory Leaks
In this page:
What is a memory leak?
Unlike a crash, a leak doesn't cause immediate visible failure -- the program keeps running, but its memory footprint grows over time, which is especially dangerous in long-running programs like servers that might run for weeks or months.
Example: What is a memory leak?
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = malloc(sizeof(int));
*ptr = 5;
printf("%d", *ptr);
free(ptr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Common causes of memory leaks
A particularly sneaky cause is reassigning a pointer variable to a new malloc() result before freeing what it previously pointed to -- the old block becomes unreachable the instant the pointer is overwritten, with no error or warning.
Example: Common causes of memory leaks
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = malloc(sizeof(int));
free(ptr);
ptr = malloc(sizeof(int));
*ptr = 5;
printf("%d", *ptr);
free(ptr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Detecting memory leaks
Dedicated tools like Valgrind can run your program and report exactly which allocations were never freed, along with the line of code that allocated them -- manual tracing works for small programs but doesn't scale well to large codebases.
Example: Detecting memory leaks
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = malloc(sizeof(int));
*ptr = 5;
printf("Run with Valgrind to detect unfreed allocations");
free(ptr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Fixing memory leaks in loops
A loop that calls malloc() on each iteration but only frees outside the loop (or not at all) can exhaust available memory surprisingly quickly, since each iteration adds another leaked block on top of the last.
Example: Fixing memory leaks in loops
#include <stdio.h>
#include <stdlib.h>
int main() {
for (int i = 0; i < 3; i++) {
int *ptr = malloc(sizeof(int));
*ptr = i;
free(ptr);
}
printf("Freed each iteration's allocation");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Memory management strategies
In larger codebases, it's common to document (in a comment or the function's name itself) whether a function transfers ownership of returned memory to the caller, since ambiguity about who's responsible for freeing something is a leading cause of leaks.
Example: Memory management strategies
#include <stdio.h>
#include <stdlib.h>
int* createValue() {
int *ptr = malloc(sizeof(int));
*ptr = 5;
return ptr;
}
int main() {
int *value = createValue();
printf("%d", *value);
free(value);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: