Skip to content
Tutorials Center
My learning

Topics

Lesson 104 of 135 ยท Advanced C

Sanitizers and Valgrind

Find memory bugs and undefined behavior in C with AddressSanitizer, UBSan, LeakSanitizer and Valgrind. Learn the flags, read the reports and fix leaks.

Most of the worst bugs in C are silent. A write one element past the end of an array, a read from freed memory or a signed overflow usually does not crash at the line that is wrong. The program keeps running with a damaged heap, and it may fail minutes later in unrelated code, or only on your customer's machine. Sanitizers and Valgrind are tools that turn these silent bugs into loud, precise error reports at the exact moment they happen.

This lesson shows how to build with AddressSanitizer (ASan), UndefinedBehaviorSanitizer (UBSan) and LeakSanitizer, how to read their reports, and how Valgrind does a similar job without recompiling. The online sandbox cannot pass compiler flags, so the compiler commands and the reports below are read-only. The two runnable examples build the same ideas by hand, so you can see how a leak detector and an overflow checker actually work. If you need a refresher on the bugs themselves, read Memory Errors and Undefined Behavior first. A shorter overview also lives in Debugging C Programs.

Two approaches: instrument or emulate

There are two ways to watch a program's memory accesses.

  • Compiler instrumentation (sanitizers). You add a flag such as -fsanitize=address. The compiler inserts extra checks around memory accesses, and a small runtime library replaces malloc and free. The slowdown is modest (about 2x for ASan), so you can run whole test suites this way.
  • Binary emulation (Valgrind). You run your normal, unmodified executable inside a virtual CPU that checks every instruction. Nothing needs recompiling, but the program runs 10 to 50 times slower.
flowchart TD
    A["Bug suspected"] --> B{"Can you rebuild<br/>the program?"}
    B -->|"yes"| C["Build with<br/>-fsanitize=address,undefined"]
    B -->|"no, binary only"| D["Run under valgrind"]
    C --> E{"Report names<br/>the bug?"}
    D --> E
    E -->|"yes"| F["Fix it, add a test"]
    E -->|"no"| G["Try -fsanitize=thread<br/>or GDB (see Debugging)"]

Rebuild with sanitizers when you can; reach for Valgrind when you cannot. Both end in a report that names the line.

Sanitizers are available in GCC and Clang on Linux and macOS, and ASan also exists in MSVC (/fsanitize=address). Valgrind runs on Linux and a few other Unix systems.

AddressSanitizer

ASan finds heap, stack and global buffer overflows, use-after-free, double free and invalid free. It works by surrounding every allocation with red zones, bytes that are marked as forbidden in a compact table called the shadow memory. Each load and store in your program is rewritten to look up the shadow byte first. Freed blocks are marked forbidden too and are kept in a quarantine for a while before reuse, which is how use-after-free is caught.

flowchart LR
    R1["red zone<br/>(forbidden)"] --- U["your 40 bytes<br/>(allowed)"] --- R2["red zone<br/>(forbidden)"]

A heap block as ASan sees it. Touching either red zone, even one byte beyond your data, stops the program with a report.

Here is a program with a classic off-by-one bug:

C
// demo.c
#include <stdlib.h>

int main(void) {
    int *numbers = malloc(10 * sizeof *numbers);
    for (int i = 0; i <= 10; i++) {   // bug: <= writes numbers[10]
        numbers[i] = i;
    }
    free(numbers);
    return 0;
}

Compile with debug info and a few helpful flags, then run it normally:

Terminal
gcc -std=c23 -g -O1 -fsanitize=address -fno-omit-frame-pointer demo.c -o demo
./demo

Without ASan this program usually "works". With ASan you get a report like this (addresses and the process ID differ on every run):

TEXT
==4120==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x502000000038 ...
WRITE of size 4 at 0x502000000038 thread T0
    #0 0x... in main demo.c:7
    #1 0x... in __libc_start_main
0x502000000038 is located 0 bytes after 40-byte region [0x502000000010,0x502000000038)
allocated by thread T0 here:
    #0 0x... in malloc
    #1 0x... in main demo.c:5
SUMMARY: AddressSanitizer: heap-buffer-overflow demo.c:7 in main

Read it from the top. The first line names the kind of bug. The WRITE of size 4 stack points to line 7, the bad access. The "0 bytes after 40-byte region" line says the write landed immediately past a 40-byte block, and the second stack shows where that block was allocated. That is usually everything you need.

Three flags are worth remembering:

Flag Why
-g Keep line numbers so reports show file and line.
-O1 Fast enough for real tests, and still close to your source. Avoid -O3 while chasing a bug.
-fno-omit-frame-pointer Gives cleaner stack traces.

ASan also catches the other usual suspects. Reading numbers[0] after free(numbers) is reported as heap-use-after-free, with three stacks: the bad access, the free that released the block and the malloc that made it. Freeing the same pointer twice is attempting double-free. A bad index on a local array is stack-buffer-overflow, and on a global it is global-buffer-overflow. Returning the address of a local variable can be caught as stack-use-after-return; depending on the compiler version this check may need ASAN_OPTIONS=detect_stack_use_after_return=1.

Finding leaks with LeakSanitizer

A memory leak is a block you allocated and never freed, with no pointer left that could free it. On Linux, ASan includes LeakSanitizer, which runs when the program exits and lists every block that is still allocated but unreachable:

C
// leak.c
#include <stdlib.h>
#include <string.h>

int main(void) {
    char *name = malloc(32);
    strcpy(name, "never freed");
    name = NULL;           // the only pointer is gone
    return 0;
}
Terminal
gcc -g -fsanitize=address leak.c -o leak && ./leak
TEXT
==4533==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 32 byte(s) in 1 object(s) allocated from:
    #0 0x... in malloc
    #1 0x... in main leak.c:5

SUMMARY: AddressSanitizer: 32 byte(s) leaked in 1 allocation(s).

A direct leak is a block nothing points to. An indirect leak is a block that is only reachable from another leaked block, for example the nodes of a linked list whose head was lost. Fixing the direct leak removes the indirect ones. You can run only the leak checker, with almost no slowdown, using -fsanitize=leak. To turn leak checking off while you look at other problems, set ASAN_OPTIONS=detect_leaks=0.

The first runnable example below builds a miniature version of this tool. It wraps malloc and free in macros that remember the file and line of each allocation, put guard bytes on both sides of every block (a tiny red zone), and print a report at the end:

C A tiny leak and overflow detector

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output names the line of every problem. A real sanitizer does the same thing with far more care: it covers every load and store, not only the ones you wrote memcpy for, and it never has to trust your own bookkeeping. But the shape (guard zones, a table of live blocks, a report at exit) is exactly the same.

UndefinedBehaviorSanitizer

UBSan catches operations that the language says have no defined result. Add it next to ASan, since the two combine well:

Terminal
gcc -std=c23 -g -O1 -fsanitize=address,undefined -fno-omit-frame-pointer main.c -o app

Instead of an abort, UBSan prints a one-line message and, by default, keeps running:

TEXT
main.c:6:15: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
main.c:9:12: runtime error: shift exponent 40 is too large for 32-bit type 'int'
main.c:12:10: runtime error: index 5 out of bounds for type 'int [3]'
main.c:15:12: runtime error: load of null pointer of type 'int'

The line and column are exact. The checks inside -fsanitize=undefined include signed overflow, shifts that are too large or negative, array bounds known at compile time, null pointer use, misaligned access, division by zero, invalid enum or bool values and reaching the end of a non-void function without returning. To make UBSan stop at the first problem, which is better in automated tests, compile with -fno-sanitize-recover=undefined or run with UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1.

UBSan complements what you can do in plain code. The second runnable example uses the compiler's overflow builtins (__builtin_add_overflow and friends, available in GCC and Clang) to check arithmetic yourself, and the predefined macros that tell code whether it is running under a sanitizer. Both of these are useful in real projects:

C Checked arithmetic and sanitizer detection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The sandbox builds without sanitizers, so the first line says "plain build". On your own machine, compile the same file with -fsanitize=address and it changes. The macro __SANITIZE_ADDRESS__ is defined by GCC (and by recent Clang), while older Clang versions use __has_feature(address_sanitizer). You can use it to skip a test that is too slow, or to disable your own custom allocator, which would hide bugs from ASan.

Other sanitizers

  • -fsanitize=thread (TSan) finds data races between threads. It cannot be combined with ASan, so use a separate build.
  • -fsanitize=memory (MSan, Clang only) finds reads of uninitialized memory, but needs every library in the program to be built with it, so it is harder to adopt.
  • -fsanitize=leak runs only LeakSanitizer.
  • -fsanitize=bounds, -fsanitize=signed-integer-overflow and others pick single checks from the UBSan family when you do not want all of them.

Sanitizers are for development and testing. They make the program slower and larger and they change its memory layout, so do not ship a sanitized build to customers.

Valgrind

Valgrind's default tool, Memcheck, needs no special build. Compile with -g so it can show line numbers, then put valgrind in front of the program:

Terminal
gcc -std=c23 -g -O0 demo.c -o demo
valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes ./demo

For the overflow program above, the beginning of the report looks like this:

TEXT
==4871== Invalid write of size 4
==4871==    at 0x1091C3: main (demo.c:7)
==4871==  Address 0x4a47068 is 0 bytes after a block of size 40 alloc'd
==4871==    at 0x484880F: malloc (vg_replace_malloc.c:442)
==4871==    by 0x10919E: main (demo.c:5)

For leaks it ends with a summary that sorts the lost memory into categories:

TEXT
==4871== LEAK SUMMARY:
==4871==    definitely lost: 32 bytes in 1 blocks
==4871==    indirectly lost: 0 bytes in 0 blocks
==4871==      possibly lost: 0 bytes in 0 blocks
==4871==    still reachable: 0 bytes in 0 blocks
Category Meaning Action
definitely lost No pointer to the block exists any more Always a bug; fix it.
indirectly lost The block is only reachable from a lost block Disappears when the parent leak is fixed.
possibly lost Only an interior pointer to the block remains Investigate; often a real leak.
still reachable A pointer still exists at exit (a global, say) Usually harmless, but tidy programs free it.

The flag --track-origins=yes makes Valgrind tell you where an uninitialized value came from when you see "Conditional jump or move depends on uninitialised value(s)". It costs extra time, so turn it on only when you meet that message. In a test script, --error-exitcode=1 makes Valgrind return a failing exit status when it finds errors, so a CI job can fail on them.

Valgrind and ASan do not combine in one run; you pick one tool per run. ASan is faster and finds stack and global overflows that Valgrind cannot see, because Valgrind does not know the sizes of stack arrays. Valgrind needs no rebuild and checks uninitialized reads precisely. Many teams use both.

A practical routine

  1. Compile your tests with -g -O1 -fsanitize=address,undefined -fno-omit-frame-pointer and run them on every change.
  2. Treat the first report as the only one that matters. Later messages are often consequences of the first bug.
  3. Fix the bug, then rerun. Add a regression test that triggers the old problem.
  4. Before a release, run the full test suite under Valgrind once, and under -fsanitize=thread if the program uses threads.
  5. Make warnings loud as well: -Wall -Wextra costs nothing and catches many bugs before the program even runs (see Debugging C Programs).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which compiler flag builds a program with AddressSanitizer?

    -fsanitize=address instruments memory accesses and links the ASan runtime. Warning flags only check code at compile time.
  2. 2. A UBSan build reports signed integer overflow: 2147483647 + 1. What does that tell you?

    UBSan prints the file, line and column of the operation. Signed overflow is undefined behavior in C, so the result cannot be trusted.
  3. 3. What is the main advantage of Valgrind over AddressSanitizer?

    Valgrind emulates the CPU, so it can check a binary you did not build with special flags. It is slower, and it cannot see the exact bounds of stack arrays.
  4. 4. In a Valgrind leak summary, which category is always a real bug that should be fixed?

    Definitely lost means no pointer to the block remains, so it can never be freed. Still-reachable blocks are usually pointers held by globals at exit.
  5. 5. Why should you not ship a build compiled with sanitizers?

    Sanitizers are test tools. Their instrumentation costs speed and memory, so release builds are compiled without them.

Summary

  • Sanitizers instrument your code at compile time; Valgrind emulates a CPU and checks an unmodified binary. Both report the exact line of a bug.
  • -fsanitize=address (ASan) finds heap, stack and global overflows, use-after-free and double free, and includes LeakSanitizer on Linux.
  • -fsanitize=undefined (UBSan) reports signed overflow, bad shifts, out-of-bounds indexes and null dereferences; add -fno-sanitize-recover=undefined to make it stop on the first problem.
  • Build with -g -O1 -fno-omit-frame-pointer for readable reports, and read the first error in a report first.
  • Thread sanitizer (-fsanitize=thread) cannot be combined with ASan; MSan is Clang-only.
  • Valgrind's --leak-check=full sorts leaks into definitely, indirectly and possibly lost, plus still reachable; --track-origins=yes explains uninitialized values.
  • Run sanitized tests on every change, but do not ship sanitized builds.

Next: I/O Multiplexing: select, poll and epoll