Memory Leaks
Find and avoid leaks.
What Is a Memory Leak
A memory leak happens when you allocate heap memory but never free it, and lose the only pointer to it.
The memory stays reserved until the program exits, wasting resources.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *p = malloc(sizeof(int));
*p = 5;
printf("%d\n", *p);
free(p);
return 0;
}Losing the Pointer
The classic leak overwrites a pointer with a new allocation before freeing the old one.
The first block becomes unreachable.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *p = malloc(sizeof(int));
free(p);
p = malloc(sizeof(int));
*p = 10;
printf("%d\n", *p);
free(p);
return 0;
}