Skip to content

Lesson 8 of 9 · 27m

Sanitizers: Make Undefined Behavior Loud

Use ASan, UBSan, TSan, and fuzzing harnesses as diagnostic instruments, understand their output, and integrate them into CI without hiding failures.

The worst undefined behavior bugs do not crash where they happen. They corrupt memory, produce a correct-looking result in tests, and explode three subsystems later under production traffic. Sanitizers move the explosion closer to the cause. They do not make C++ safe, but they make some categories of unsafety honest. Your job is to run the right sanitizer in the right configuration and read the output instead of treating it as compiler vomit.

ASan finds memory errors near the crime scene

AddressSanitizer detects use-after-free, heap and stack overflow, some container overflows, and double-free:

clang++ -std=c++20 -g -O1 -fsanitize=address -fno-omit-frame-pointer     src/main.cpp -o netd-asan
./netd-asan --self-test

A useful report names the invalid access, allocation stack, and free stack:

ERROR: AddressSanitizer: heap-use-after-free
READ of size 8 at 0x6040000012f0
    #0 Session::write() src/session.cpp:81
    #1 handle_frame() src/main.cpp:44

freed by thread T0 here:
    #2 Session::~Session() src/session.cpp:30

Read bottom-up as ownership history. The crash line is only where the corrupted state became visible.

UBSan catches language-level lies

UndefinedBehaviorSanitizer catches integer overflow in signed arithmetic, bad shifts, misaligned access, invalid enum loads, null dereference, and more:

clang++ -std=c++20 -g -O1 -fsanitize=undefined     -fno-sanitize-recover=all src/main.cpp -o netd-ubsan

Use -fno-sanitize-recover=all in tests so execution stops at the first violation. A recoverable runtime is useful for exploration but terrible in CI because programs can pass after emitting reports.

TSan needs a different build and a different mindset

ThreadSanitizer detects data races, but not every race is obvious shared mutable state. Lifecycle races dominate modern services: object destroyed while worker still uses it, callback captures stale reference, shutdown publishes state without synchronization.

clang++ -std=c++20 -g -O1 -fsanitize=thread src/main.cpp -o netd-tsan

TSan conflicts with ASan; run separate binaries. It also relies on happens-before edges it can observe. Correct mutex use, atomics with deliberate memory ordering, and clear ownership transfer produce clean reports. Ad-hoc flags and volatile do not.

Wire sanitizers through CMake, not hero commands

option(NETD_ENABLE_ASAN "Enable AddressSanitizer" OFF)
if(NETD_ENABLE_ASAN)
    target_compile_options(netd_core PRIVATE -fsanitize=address -fno-omit-frame-pointer)
    target_link_options(netd_core PRIVATE -fsanitize=address)
endif()

Apply instrumentation consistently to enough of the dependency graph that allocation and deallocation interception stays coherent. System libraries are often uninstrumented, which is fine; your code must not mix incompatible runtimes or interceptors accidentally.

Fuzzing finds inputs; sanitizers interpret them

libFuzzer plus ASan/UBSan is how parsers earn trust:

extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t* data, size_t size) {
    parse_header({reinterpret_cast<const char*>(data), size});
    return 0;
}

The fuzzer discovers bytes. The sanitizer explains why those bytes matter. Minimize crashing inputs and add them as regression tests; otherwise the corpus is just an incident archive.

Field notes

  • Use -O1 or -O2 rather than -O0 for many sanitizer builds so behavior resembles optimized production while retaining diagnostics.
  • LeakSanitizer is commonly enabled with ASan on Linux; ASAN_OPTIONS=detect_leaks=0 can silence leaks, but understand what you are hiding first.
  • Do not ship sanitizer-instrumented production artifacts casually; they have performance, security, and operational implications.
  • A clean sanitizer run is evidence about executed paths only. It proves nothing for inputs and threads you did not exercise.

Was this lesson helpful?

Sign in to rate