Skip to main content

Lesson 4 of 5

valgrind & ASAN - Memory Error Detection Tools

Two complementary tools for finding memory bugs: **valgrind** (dynamic binary instrumentation - slow but comprehensive, no recompile needed) and **AddressSanitizer / UBSan** (compile-time instrumentation - ~2x slower than unsan, much faster than valgrind, both heap and stack detection). In production development, ALWAYS run both during testing.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

valgrind & ASAN - Command Reference & Reading Output

valgrind & ASAN - Command Reference & Reading Output
# ═══════════════════════════════════════════════════════════
# VALGRIND - comprehensive memory checking
# ═══════════════════════════════════════════════════════════

# Build (normal compile - no special flags needed):
gcc -Wall -g -O0 program.c -o program

# Run with full leak checking:
valgrind --leak-check=full          --show-leak-kinds=all          --track-origins=yes          --error-exitcode=1          ./program

# ── Key valgrind flags ───────────────────────────────────────
# --leak-check=full       Show each individual leak
# --show-leak-kinds=all   Include indirect/reachable leaks
# --track-origins=yes     Show where uninitialised values came from
# --error-exitcode=N      Exit N if any errors found (for CI)
# --gen-suppressions=all  Generate suppression file for false positives

# ── Reading valgrind output ──────────────────────────────────
# == Invalid read of size 4
#    at 0x...: func_name (file.c:42)   ← where it happened
#    Address 0x... is 0 bytes after a block of size 16 alloc'd  ← what is at that address
#    at 0x...: malloc (vgpreload)
#    by 0x...: alloc_func (file.c:10)  ← where block was allocated
#
# == 40 bytes in 1 blocks are definitely lost
#    at 0x...: malloc
#    by 0x...: create_something (file.c:15)  ← the leaking allocation

# ── valgrind callgrind - performance profiling ───────────────
valgrind --tool=callgrind --callgrind-out-file=cg.out ./program
callgrind_annotate cg.out | head -50
# kcachegrind cg.out   # visual GUI alternative

# ═══════════════════════════════════════════════════════════
# AddressSanitizer (ASAN) + UBSan - compile-time instrumentation
# ═══════════════════════════════════════════════════════════

# Build with sanitizers:
gcc -Wall -g -O1     -fsanitize=address,undefined     -fno-omit-frame-pointer     program.c -o program_asan

# Run normally:
./program_asan

# ── What ASAN detects ────────────────────────────────────────
# - Heap buffer overflow    (past end of malloc'd block)
# - Stack buffer overflow   (past end of local array)
# - Use after free          (reading freed memory)
# - Use after scope         (pointer to gone local variable)
# - Double free
# - Memory leaks (with ASAN_OPTIONS=detect_leaks=1)

# ── What UBSan detects ───────────────────────────────────────
# - Integer overflow        (signed int overflow = UB)
# - Null pointer dereference
# - Invalid shift           (shift by >= type width)
# - Misaligned memory access
# - Type punning via cast   (strict aliasing violation)

# ── Reading ASAN output ──────────────────────────────────────
# == ERROR: AddressSanitizer: heap-buffer-overflow
# READ of size 4 at 0x... thread T0
#    #0 0x...  in process_array file.c:25
#    #1 0x...  in main file.c:40
# 0x... is located 0 bytes after 40-byte region [0x..., 0x...)
# allocated by thread T0 here:
#    #0 0x...  in malloc ...
#    #1 0x...  in create_array file.c:10

# ── ASAN environment options ─────────────────────────────────
ASAN_OPTIONS=detect_leaks=1:print_stats=1 ./program_asan
ASAN_OPTIONS=halt_on_error=0 ./program_asan   # continue after first error

# ── Choosing between valgrind and ASAN ──────────────────────
# ASAN:    faster (2x), detects stack overflows, needs recompile
# valgrind: slower (20x), no recompile, better leak origins tracking
# Use both: ASAN in dev loop, valgrind for deep analysis
Diagram
Loading diagram…

ASan and Valgrind catch memory corruption, buffer overflows, and leaks before production release

Common Mistakes

  • Not checking valgrind's exit code in CI - `valgrind ./test` exits 0 even with errors by default. Add `--error-exitcode=1` so CI pipelines correctly fail on memory bugs.
  • Building with `-O2` for valgrind/ASAN - some bugs only appear under optimisation, but some (uninitialised variable trackability) are easier to find at `-O0`. Test at both levels.
  • Ignoring 'possibly lost' leaks in valgrind - 'definitely lost' is a leak. 'Possibly lost' means the only pointer to the allocation has been modified (e.g., stored mid-block). Both need investigation.

Key Takeaways

  • Two complementary tools for finding memory bugs: **valgrind** (dynamic binary instrumentation - slow but comprehensive, no recompile needed) and **AddressSanitizer / UBSan** (compile-time instrumentation - ~2x slower than unsan, much faster than valgrind, both heap and stack detection).
  • Not checking valgrind's exit code in CI - `valgrind ./test` exits 0 even with errors by default. Add `--error-exitcode=1` so CI pipelines correctly fail on memory bugs.
  • Building with `-O2` for valgrind/ASAN - some bugs only appear under optimisation, but some (uninitialised variable trackability) are easier to find at `-O0`. Test at both levels.
  • Ignoring 'possibly lost' leaks in valgrind - 'definitely lost' is a leak. 'Possibly lost' means the only pointer to the allocation has been modified (e.g., stored mid-block). Both need investigation.

Topics in This Module

0/5 done