How to Fix Memory Leak in C: Simple Steps and Examples
A memory leak in C happens when you allocate memory with
malloc but forget to release it with free. To fix it, always pair every malloc with a corresponding free when the memory is no longer needed.Why This Happens
Memory leaks occur when a program allocates memory but never releases it back to the system. This causes the program to use more and more memory over time, which can slow down or crash the program.
In C, this usually happens when you use malloc to get memory but forget to call free to release it.
c
#include <stdio.h> #include <stdlib.h> int main() { int *ptr = (int *)malloc(sizeof(int) * 5); // allocate memory if (ptr == NULL) { printf("Memory allocation failed\n"); return 1; } // use ptr here ptr[0] = 10; printf("First element: %d\n", ptr[0]); // forgot to free memory return 0; }
Output
First element: 10
The Fix
To fix the memory leak, you must call free on the pointer when you no longer need the allocated memory. This returns the memory to the system and prevents leaks.
c
#include <stdio.h> #include <stdlib.h> int main() { int *ptr = (int *)malloc(sizeof(int) * 5); // allocate memory if (ptr == NULL) { printf("Memory allocation failed\n"); return 1; } ptr[0] = 10; printf("First element: %d\n", ptr[0]); free(ptr); // free allocated memory return 0; }
Output
First element: 10
Prevention
To avoid memory leaks in the future, always:
- Match every
mallocorcallocwith afree. - Set pointers to
NULLafter freeing to avoid using freed memory. - Use tools like Valgrind to detect leaks during testing.
- Keep your code organized so you clearly see where memory is allocated and freed.
Related Errors
Other common memory-related errors include:
- Double free: Calling
freetwice on the same pointer causes crashes. - Use after free: Accessing memory after it has been freed leads to undefined behavior.
- Buffer overflow: Writing outside allocated memory corrupts data and causes crashes.
Fix these by careful memory management and using debugging tools.
Key Takeaways
Always free memory allocated with malloc to prevent leaks.
Use tools like Valgrind to find memory leaks during development.
Set pointers to NULL after freeing to avoid accidental reuse.
Organize code to clearly track memory allocation and deallocation.
Avoid double free and use-after-free errors by careful pointer handling.