What are the common causes and detection methods for memory leaks in C language?
Common Memory Leak Causes:
-
Unreleased Dynamically Allocated Memory
cvoid leak_example() { int *ptr = malloc(sizeof(int) * 100); // Forgot to call free(ptr) } -
Double Free from Repeated Deallocation
cint *ptr = malloc(sizeof(int)); free(ptr); free(ptr); // Undefined behavior -
Pointer Overwrite Causing Unreachable Memory
cint *ptr = malloc(sizeof(int) * 10); ptr = malloc(sizeof(int) * 20); // Original memory leaked -
Memory Leaks in Circular References
- Structures referencing each other forming loops
- Reference count never reaches zero
-
Unreleased Memory in Exception Handling Paths
- Early function returns forget to free
- Error handling branches miss free calls
Detection Methods:
-
Valgrind Tool
bashvalgrind --leak-check=full --show-leak-kinds=all ./program -
AddressSanitizer
bashgcc -fsanitize=address -g program.c -o program -
Code Review
- Check all malloc/calloc/realloc have corresponding free
- Review memory release on all function return paths
Prevention Measures:
- Use RAII pattern (C++ style)
- Establish memory allocation/deallocation pairing checks
- Use smart pointer wrappers (C++)
- Regular memory analysis tool checks