Skip to main content
Be Bitwise
CAdvanced Memory in C

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.

Tools come next. First, name the enemies:

  1. Memory leak: Allocated memory that is never freed. The program's memory usage grows without bound.
  2. Use-after-free (UAF): Accessing memory after calling free(). May read stale data or crash.
  3. Buffer overflow: Writing past the end of an allocated buffer. Corrupts adjacent memory.
  4. Double free: Calling free() on the same pointer twice. Corrupts the allocator's internal state.
  5. Uninitialized read: Reading memory that was never written to. Returns garbage values.
  6. 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:

bash
gcc -g -O0 program.c -o program
valgrind --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:

c
==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:

c
==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:

c
==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'd
Key Concept

Valgrind 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:

bash
gcc -fsanitize=address -g -O1 program.c -o program
./program

ASan 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:

c
==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000014
WRITE 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 region
allocated by thread T0 here:
#0 0x7f... in malloc
#1 0x4005c0 in main program.c:6

Here'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

FeatureValgrindASan
Overhead10-50x slower2x slower
Recompilation neededNoYes
Leak detectionExcellentGood on Linux (LeakSanitizer is built in); not available everywhere
Stack overflow detectionNoYes
Global buffer overflowNoYes
AvailabilitySeparate toolBuilt 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:

bash
clang -fsanitize=memory -g program.c -o program
c
int main() {
int x;
if (x > 0) { // MSan catches this: x is uninitialized
printf("positive\n");
}
return 0;
}

MSan output:

c
==WARNING: MemorySanitizer: use-of-uninitialized-value
#0 0x4005a0 in main program.c:3

Interpreting Sanitizer Output

When a sanitizer screams, read the report top-to-bottom:

  1. Error type: What kind of bug (heap-buffer-overflow, use-after-free, etc.)
  2. Access details: Where the bad access happened (file, line, function)
  3. Allocation info: Where the relevant memory was allocated
  4. 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

bash
# In your Makefile
CFLAGS_DEBUG = -fsanitize=address -g -O1 -fno-omit-frame-pointer

Step 2: Run your test suite with ASan

bash
make debug
./run_tests

Step 3: For leaks, use Valgrind

bash
valgrind --leak-check=full --show-leak-kinds=all ./program

Step 4: For uninitialized reads, use MSan

bash
clang -fsanitize=memory -g program.c -o program
./program

Step 5: Add sanitizers to CI

yaml
# Example CI step
- name: Test with sanitizers
run: |
make CFLAGS="-fsanitize=address -g" test
make CFLAGS="-fsanitize=undefined -g" test

UndefinedBehaviorSanitizer (UBSan)

Catches undefined behaviour: signed integer overflow, null pointer dereference, misaligned access, the lot:

bash
gcc -fsanitize=undefined -g program.c -o program
c
#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:

  1. Initialize all variables: int x = 0; not int x;
  2. Check array bounds: Before every index, verify it is in range.
  3. Set pointers to NULL after free: free(p); p = NULL;
  4. Use sizeof with the variable, not the type: malloc(sizeof(*p)) not malloc(sizeof(int))
  5. 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.
  6. Use snprintf, not sprintf: Bounded writes prevent overflows.
  7. 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.