Debugging Memory Issues
Memory bugs in C are some of the meanest defects you'll ever chase. A use-after-free will pass every test you throw at it, then corrupt data once it hits production. A buffer overflow can quietly stomp on an unrelated variable for weeks. A memory leak only bares its teeth after the process has been running for days. Good news: there's serious tooling for catching this stuff early.
The Rogues Gallery of Memory Bugs
Tools come next. First, name the enemies:
- Memory leak: Allocated memory that is never freed. The program's memory usage grows without bound.
- Use-after-free (UAF): Accessing memory after calling
free(). May read stale data or crash. - Buffer overflow: Writing past the end of an allocated buffer. Corrupts adjacent memory.
- Double free: Calling
free()on the same pointer twice. Corrupts the allocator's internal state. - Uninitialized read: Reading memory that was never written to. Returns garbage values.
- Stack buffer overflow: Writing past the end of a local array. Overwrites the return address, enabling exploits.
Valgrind Memcheck
Valgrind is the elder statesman of memory debuggers. It instruments your program at runtime, watching every allocation and every access:
gcc -g -O0 program.c -o programvalgrind --leak-check=full ./program-g keeps debug symbols around so Valgrind can map errors back to source lines. -O0 switches optimisations off so the code matches what you actually wrote.
Here's the kind of report Valgrind hands you for each class of bug:
Memory leak:
==12345== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1==12345== at 0x4C2A10: malloc (vg_replace_malloc.c:307)==12345== by 0x400567: create_data (program.c:15)==12345== by 0x4005A0: main (program.c:22)Use-after-free:
==12345== Invalid read of size 4==12345== at 0x400540: main (program.c:10)==12345== Address 0x5204040 is 0 bytes inside a block of size 4 free'd==12345== at 0x4C2B50: free (vg_replace_malloc.c:538)==12345== by 0x400530: main (program.c:9)Buffer overflow:
==12345== Invalid write of size 1==12345== at 0x400560: fill_buffer (program.c:7)==12345== by 0x4005A0: main (program.c:14)==12345== Address 0x5204050 is 0 bytes after a block of size 16 alloc'dValgrind drags your program down by 10-50x because it runs your program on a synthetic CPU: it translates each block of machine code into an intermediate form, adds checks to every memory access, and recompiles it on the fly. Don't run it in production. Do bake it into dev workflow and CI.
AddressSanitizer (ASan)
AddressSanitizer lives inside the compiler instead of an external interpreter, and it's far quicker than Valgrind — usually around a 2x slowdown. Both GCC and Clang ship it:
gcc -fsanitize=address -g -O1 program.c -o program./programASan catches the same family of bugs Valgrind does but takes a different route: it injects checks around every memory access at compile time and keeps a shadow memory map tracking which bytes are valid.
ASan output for a heap buffer overflow:
==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000014WRITE of size 4 at 0x602000000014 thread T0 #0 0x4005f0 in main program.c:8 #1 0x7f... in __libc_start_main
0x602000000014 is located 0 bytes to the right of 4-byte regionallocated by thread T0 here: #0 0x7f... in malloc #1 0x4005c0 in main program.c:6Here's the shadow memory behind that report. Every 8-byte granule of application memory gets one shadow byte, found at (addr >> 3) + 0x7fff8000 on x86-64 Linux. 00 means all eight bytes are usable, a value from 1 to 7 means only that many leading bytes are, and fa marks a heap redzone that no valid access should ever reach. The 4-byte block at 0x602000000010 gets a shadow byte of 04, so the write at 0x...14, offset 4 in that granule, trips the check.
Comparing Valgrind and ASan
| Feature | Valgrind | ASan |
|---|---|---|
| Overhead | 10-50x slower | 2x slower |
| Recompilation needed | No | Yes |
| Leak detection | Excellent | Good on Linux (LeakSanitizer is built in); not available everywhere |
| Stack overflow detection | No | Yes |
| Global buffer overflow | No | Yes |
| Availability | Separate tool | Built into compiler |
MemorySanitizer (MSan)
MemorySanitizer detects reads of uninitialized memory. It's Clang-only and runs on Linux and the BSDs (no macOS), and it wants every line of code in the process instrumented, libraries included. Uninstrumented code produces false reports, so a C++ program needs a libc++ built with -fsanitize=memory; for plain C, the runtime's interceptors cover the common libc calls:
clang -fsanitize=memory -g program.c -o programint main() { int x; if (x > 0) { // MSan catches this: x is uninitialized printf("positive\n"); } return 0;}MSan output:
==WARNING: MemorySanitizer: use-of-uninitialized-value #0 0x4005a0 in main program.c:3Interpreting Sanitizer Output
When a sanitizer screams, read the report top-to-bottom:
- Error type: What kind of bug (heap-buffer-overflow, use-after-free, etc.)
- Access details: Where the bad access happened (file, line, function)
- Allocation info: Where the relevant memory was allocated
- Free info (for UAF): Where the memory was freed
Use the stack traces to walk the lifecycle of the offending memory:
- Where did it get allocated?
- Where (if anywhere) was it freed?
- Where did the bad access happen?
Practical Debugging Workflow
A practical loop for hunting memory bugs:
Step 1: Compile with ASan during development
# In your MakefileCFLAGS_DEBUG = -fsanitize=address -g -O1 -fno-omit-frame-pointerStep 2: Run your test suite with ASan
make debug./run_testsStep 3: For leaks, use Valgrind
valgrind --leak-check=full --show-leak-kinds=all ./programStep 4: For uninitialized reads, use MSan
clang -fsanitize=memory -g program.c -o program./programStep 5: Add sanitizers to CI
# Example CI step- name: Test with sanitizers run: | make CFLAGS="-fsanitize=address -g" test make CFLAGS="-fsanitize=undefined -g" testUndefinedBehaviorSanitizer (UBSan)
Catches undefined behaviour: signed integer overflow, null pointer dereference, misaligned access, the lot:
gcc -fsanitize=undefined -g program.c -o program#include <limits.h>
int main() { int x = INT_MAX; x = x + 1; // UBSan catches: signed integer overflow return 0;}Writing Memory-Safe C
Tools catch bugs after they exist. Habits below prevent them in the first place:
- Initialize all variables:
int x = 0;notint x; - Check array bounds: Before every index, verify it is in range.
- Set pointers to NULL after free:
free(p); p = NULL; - Use
sizeofwith the variable, not the type:malloc(sizeof(*p))notmalloc(sizeof(int)) - Think before reaching for
calloc: zeroed memory turns a garbage read into a predictable one, which is safer in production, but it also hides "forgot to initialise" bugs from Valgrind and MSan. Initialise fields deliberately rather than relying on the zeroing. - Use
snprintf, notsprintf: Bounded writes prevent overflows. - Run sanitizers in CI: Every commit, every pull request.
Sanitizers aren't a nice-to-have. In serious C work, running them should feel as routine as running the test suite itself.