Sanitizers Deep Dive
Memory Safety & Debugging · Memory & Systems track
7 min read
In this module
Compile-Time Instrumentation for Runtime Detection
Sanitizers are compiler features that splice extra checks into your program at compile time. Those checks run alongside your code, catching memory errors, data races, and undefined behaviour as they happen. They're the most effective tools for finding memory bugs in C/C++ code.
Sanitizers are compile-time hooks that bake runtime checks into your binary. Trade some performance, gain a clear backtrace the moment a memory bug actually happens.
AddressSanitizer (ASan)
AddressSanitizer flags buffer overflows, use-after-free, double-free, and other spatial and temporal memory errors. Available in GCC and Clang via -fsanitize=address.
Shadow memory: ASan maps every 8 bytes of application memory to 1 byte of shadow memory. The shadow byte encodes accessibility — 0 means all 8 bytes are accessible, 1-7 means the first N bytes are accessible (the rest is padding), and negative values flag different types of inaccessible memory (stack red zone, heap red zone, freed memory, and so on).
Red zones: ASan drops "red zones" around every stack variable, heap allocation, and global. The red zones get poisoned in shadow memory. Touch one and ASan trips on the spot.
Stack layout with ASan:[red zone] [local var a] [red zone] [local var b] [red zone] ^^^^^^^^^^ This red zone catches overflow from a into bQuarantine: freed memory doesn't go straight back to the allocator. ASan parks it in a quarantine — a FIFO queue of recently freed memory that stays poisoned. Use-after-free? ASan catches it. The quarantine is bounded; once it fills, the oldest entries actually get freed.
$ clang -fsanitize=address -g program.c -o program$ ./program===================================================================12345==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000050WRITE of size 1 at 0x602000000050 thread T0 #0 0x4f3c37 in process_input /src/program.c:42:5 ...0x602000000050 is located 0 bytes to the right of 16-byte region [0x602000000040,0x602000000050)allocated by thread T0 here: #0 0x4c7c08 in malloc #1 0x4f3b91 in process_input /src/program.c:38:18Here's how ASan knew. The 16-byte block in that report covers two 8-byte chunks, and each chunk has one shadow byte. On x86-64 Linux the shadow byte for any address sits at (addr >> 3) + 0x7fff8000:
Before every load or store, the instrumented code shifts the address right by 3, adds the offset and reads one byte. The write to 0x602000000050 finds fa, and the report fires. Had the block been 13 bytes instead of 16, the second shadow byte would read 05, meaning only the first five bytes of that chunk are usable.
On Linux, ASan also runs LeakSanitizer at exit by default, reporting heap blocks that nothing points to any more.
ASan tax: roughly 2x slowdown and 2-3x memory growth. Fine for testing and development.
To see why that's worth paying, run this without ASan. It writes one byte past an 8-byte heap block, and the in-browser runner builds it with no sanitizer flags.
The allocator rounds small blocks up, so that stray byte lands in slack space and the program looks healthy. Build the same file with -fsanitize=address -g on your own machine and it stops on the first bad write.
Before opening: which two line numbers will the ASan report point at?
==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000018WRITE of size 1 at 0x602000000018 thread T0 #0 in main main.c:90x602000000018 is located 0 bytes after 8-byte region [0x602000000010,0x602000000018)allocated by thread T0 here: #0 in malloc #1 in main main.c:5Shadow bytes around the buggy address:=>0x0c047fff8000: fa fa 00[fa]fa fa fa fa ...Line 9 is the faulting write (name[i] = 'A' when i is 8), and line 5 is the malloc that created the block. "0 bytes after 8-byte region" says the write landed immediately past the end, the classic off-by-one. In the shadow bytes, 00 is the block's 8 good bytes and [fa] is the heap red zone the write hit. Addresses differ on every machine, and older ASan versions word it as "0 bytes to the right of".
ASan has blind spots. It cannot detect uninitialised reads (use MSan for that), data races (use TSan), or an overflow that jumps clean over the red zone and lands inside a different valid allocation (a large or attacker-controlled index can do this). It also cannot detect logic errors where memory is accessed correctly but the program misinterprets the data. Combine ASan with other sanitizers and testing techniques to fill the gaps. On AArch64, HWASan and Arm's Memory Tagging Extension (MTE) take a different approach, tagging pointers and memory so a mismatch is caught however far the access strays, though only probabilistically.
MemorySanitizer (MSan)
MemorySanitizer catches uses of uninitialised memory. Like ASan, it leans on shadow memory — but instead of tracking accessibility, it tracks definedness: whether each byte has been written (initialised) or not.
MSan marks all memory from malloc, stack allocations, and mmap as uninitialised. When the program writes to memory, MSan flips those bytes to initialised. When an uninitialised value affects observable behaviour (a conditional branch, a syscall argument, an address calculation), MSan reports an error.
MSan demands that the entire program — every library included — be compiled with -fsanitize=memory. Skip a library and MSan may produce false positives (it can't see those writes) or miss bugs (the library quietly propagates uninitialised data). That makes MSan harder to deploy than ASan.
MSan and ASan can't run together. They share shadow memory regions.
ThreadSanitizer (TSan)
ThreadSanitizer catches data races: unsynchronised concurrent accesses to the same memory location where at least one is a write. TSan instruments every memory access and synchronisation operation, building a happens-before graph.
Per memory location, TSan tracks the last few accesses (thread ID, timestamp, read/write type). When a fresh access lands, TSan checks whether any previous access by a different thread conflicts — same location, at least one write, no synchronisation ordering them. If so, it reports a data race.
$ clang -fsanitize=thread -g program.c -o program -lpthread$ ./programWARNING: ThreadSanitizer: data race (pid=12345) Write of size 4 at 0x7f8a2c000000 by thread T1: #0 increment /src/program.c:15:5 Previous read of size 4 at 0x7f8a2c000000 by thread T2: #0 read_counter /src/program.c:22:12TSan's overhead is steeper: 5-15x slowdown, 5-10x memory growth, because it has to track temporal ordering across threads. It can't share a build with ASan either: clang rejects -fsanitize=address,thread outright, so races and memory errors need separate test runs.
UBSan: Undefined Behaviour Sanitizer
UBSan catches undefined behaviour the C/C++ standards prohibit but compilers usually don't check. Lightweight (single-digit percentage overhead) and combinable with ASan and TSan.
UBSan flags signed integer overflow, unsigned integer overflow (optional, since it's technically defined but often unintended), division by zero, null pointer dereference, misaligned pointer access, out-of-bounds array indexing, invalid shift amounts, invalid enum values, invalid bool values, and plenty more.
$ clang -fsanitize=undefined -g program.c -o program$ ./programprogram.c:12:15: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'UBSan is the cheapest sanitizer and should run on every dev and test build. Plenty of undefined behaviours that "work fine on my machine" go sideways on a different architecture, compiler version, or optimisation level.
Combining Sanitizers
The pragmatic strategy: always enable UBSan — it's cheap. Reach for ASan for memory error detection (the most consequential class of bugs). Use TSan on multi-threaded code. Pull out MSan when you can instrument the entire dependency chain. Run your test suite under each configuration, since they catch different bug classes that don't always overlap. You'll need separate builds anyway: ASan, TSan and MSan each claim the address space for their own shadow memory, so no two of them can share a binary.