03. Memory Leak Detection, Valgrind & AddressSanitizer
🔴 Difficulty: Advanced | Heap Leak Hazards, Valgrind Memcheck & GCC AddressSanitizer (-fsanitize=address)
📖 Definition
A memory leak occurs when a program allocates dynamic memory on the system Heap (via malloc, calloc, or realloc) but loses all pointer references to the allocated block without calling free(). Automated memory auditing tools like Valgrind Memcheck and AddressSanitizer (ASan) intercept heap calls to detect leaks, use-after-free, and out-of-bounds heap accesses.
🎯 Why It Is Used
- Preventing Server Outages: Long-running servers or background daemons with memory leaks eventually consume all available RAM, triggering the Operating System Out-Of-Memory (OOM) Killer.
- Automated CI/CD Quality Gates: Running GCC AddressSanitizer flags memory safety bugs during automated unit test executions before code is merged into production.
⚙️ How It Works: Valgrind vs GCC AddressSanitizer (ASan)
| Sanitizer Tool | How It Operates | Compilation Flag Required | Runtime Overhead |
|---|---|---|---|
| AddressSanitizer (ASan) | Instruments binaries at compile time with shadow memory checks. | gcc -fsanitize=address -g main.c |
Fast (~2x overhead) |
| Valgrind Memcheck | Runs uninstrumented binary inside a synthetic virtual CPU. | gcc -g main.c → valgrind ./a.out |
Slower (~20x overhead) |
📝 Syntax: Running Compiler Sanitizers
# 1. Compile with GCC / Clang AddressSanitizer
gcc -Wall -Wextra -std=c11 -fsanitize=address -g leaky_program.c -o leaky_program
# 2. Execute binary directly (ASan intercepts memory bugs automatically!)
./leaky_program
# 3. Running Valgrind Full Leak Check
gcc -g leaky_program.c -o leaky_program
valgrind --leak-check=full --show-leak-kinds=all ./leaky_program
🔀 Common Memory Safety Violations
- Direct Memory Leak: Losing the pointer address of allocated heap memory without freeing it.
- Use-After-Free (UAF): Accessing or modifying heap memory after calling
free(ptr). - Heap Buffer Overflow: Writing past the allocated byte bounds of a
malloc()block. - Double Free: Calling
free(ptr)twice on the same memory block.
🌱 Beginner Example: Intentional Memory Leak for Analysis
#include <stdio.h>
#include <stdlib.h>
void cause_memory_leak(void) {
int *leaked_buffer = (int*)malloc(100 * sizeof(int));
if (leaked_buffer == NULL) return;
leaked_buffer[0] = 999;
printf("Buffer value: %d\n", leaked_buffer[0]);
// INTENTIONAL BUG: 'free(leaked_buffer)' is OMITTED!
// 'leaked_buffer' local pointer variable is destroyed on return,
// leaving 400 bytes stranded on the heap forever!
}
int main(void) {
cause_memory_leak();
printf("Function returned, but 400 heap bytes are LEAKED!\n");
return 0;
}
🌼 Intermediate Example: Corrected Leak-Free Implementation
#include <stdio.h>
#include <stdlib.h>
void process_clean_buffer(void) {
int *clean_buffer = (int*)malloc(100 * sizeof(int));
if (clean_buffer == NULL) return;
clean_buffer[0] = 999;
printf("Buffer value: %d\n", clean_buffer[0]);
// SAFE: Explicitly free heap memory before stack frame exit!
free(clean_buffer);
clean_buffer = NULL;
}
int main(void) {
process_clean_buffer();
printf("Function returned cleanly. 0 bytes leaked!\n");
return 0;
}
🌲 Advanced Example: Simulating Use-After-Free for ASan Detection
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *heap_val = (int*)malloc(sizeof(int));
if (heap_val == NULL) return 1;
*heap_val = 42;
free(heap_val); // Memory freed
// USE-AFTER-FREE BUG: Accessing freed memory!
// ASan (-fsanitize=address) catches this crash immediately!
// printf("Freed Value: %d\n", *heap_val);
heap_val = NULL; // Defensive nullification prevents UAF!
return 0;
}
🔍 Line-by-Line Explanation
int *leaked_buffer = malloc(...): Allocates 400 bytes on the heap.// free(leaked_buffer);: Omitting this line causes Valgrind to report "400 bytes in 1 blocks are definitely lost".gcc -fsanitize=address -g: Instruments binary to output exact file names and line numbers when memory bugs occur.
💻 Expected Terminal Output
Buffer value: 999
Function returned, but 400 heap bytes are LEAKED!
=== Valgrind Analysis Output Preview ===
==12345== HEAP SUMMARY:
==12345== in use at exit: 400 bytes in 1 blocks
==12345== 400 bytes in 1 blocks are definitely lost in loss record 1 of 1
==12345== at 0x483B7F3: malloc (vg_replace_malloc.c:309)
==12345== by 0x109156: cause_memory_leak (main.c:6)
==12345== LEAK SUMMARY:
==12345== definitely lost: 400 bytes in 1 blocks
⚠️ Common Mistakes & Pitfalls
- Overwriting Pointers Before Freeing: Writing
ptr = malloc(20); ptr = malloc(40);leaks the first 20-byte block because its address was overwritten! - Early Returns Skipping
free(): Returning early from a function on error conditions (e.g.if (error) return -1;) without freeing allocated heap buffers.
📌 Important Rules & Limitations
- Always pair every
malloc/calloc/reallocwith a correspondingfree()before losing pointer scope. - Compile and test debug builds with
gcc -fsanitize=address -gto catch memory corruption during development.
🌐 Multilingual Explanation: English
A memory leak occurs when heap memory is not freed before losing its pointer reference. Use GCC AddressSanitizer (-fsanitize=address) or Valgrind to automatically find leaks and Use-After-Free bugs.
🌐 Multilingual Explanation: Hindi (Roman Script)
Jab aap heap memory allocate karke free() karna bhool jate hain, toh use Memory Leak kehte hain. Memory leaks aur Use-After-Free bugs dhoondhne ke liye gcc -fsanitize=address ya Valgrind ka upyog karein.
🌐 Multilingual Explanation: Marathi (Roman Script)
Heap memory free() na kelyas Memory Leak hoto. Memory leaks shodhnayasathi gcc -fsanitize=address kiva Valgrind tool vapra.
❓ Practice Questions
- What is a memory leak and what are its consequences in server applications?
- How do you compile a C program with GCC AddressSanitizer (ASan)?
- What is a Use-After-Free (UAF) bug?
🚀 Practical Coding Challenge
Write a C program named audit_clean_list.c that dynamically allocates a linked list of 5 nodes, populates them, and implements a cleanup function void free_list(Node *head) that traverses and frees every node without memory leaks.
🧭 Navigation & Breadcrumbs
← Previous: 02. Dynamic Resizing with realloc() | Module 12 Guide | Next Module: 13. Structures & Alignment →