skip to content

Sanitizers and Hardening

-fsanitize=address, undefined and thread instrument a build to catch memory errors, UB and races at run time. Interviewers ask which sanitizer finds which bug and what it costs.

on this pageshow

explore

questions

5

With GCC, what does -fsanitize=address detect, and how do you read its report for a use-after-free in a server?

level: middleimportance: must knowfreq 66%

answer

  1. instrumented loads and stores
  2. out of bounds and after free
  3. access, free, allocation: three stacks
  4. -g and frame pointers
  5. roughly twice as slow

basics

~20 s

-fsanitize=address instruments memory accesses to catch out-of-bounds reads and writes on the heap, stack and globals, use-after-free and use-after-scope. Its report shows the bad access's stack, then where that memory was freed and where it was allocated.

solid answer

~40 s

AddressSanitizer is compile-time instrumentation plus a run-time library: every load and store is checked against shadow memory that marks redzones around objects and memory already freed. With GCC, `-fsanitize=address` must be on the compile and the link; the manual recommends `-g`, and `-fno-omit-frame-pointer` plus `-O1` or `-Og` give more accurate stacks. A report starts with the bug kind, such as `heap-use-after-free`, and the access size, then the stack of the bad access; for freed memory it adds a 'freed by' stack and a 'previously allocated by' stack. Read the first frame in your own code in each: that gives the use, the free and the allocation. Clang's documentation puts the typical slowdown at about 2x, and ASan cannot be combined with `-fsanitize=thread`.

code

cpp · 16 lines
cpp
#include <cstdio>
#include <vector>

struct Session { int id; };

int main() {
    std::vector<Session*> sessions;
    for (int i = 0; i < 4; ++i) sessions.push_back(new Session{i});

    Session* stale = sessions[2];
    delete sessions[2];                 // connection closed
    sessions.erase(sessions.begin() + 2);

    std::printf("id=%d\n", stale->id);  // use-after-free: undefined behaviour
    for (Session* s : sessions) delete s;
}

go deeper

for a junior

Know that -fsanitize=address catches out-of-bounds accesses and use-after-free at run time, and that you build with -g to get readable reports.

for a middle

Read the three stacks in a report, explain redzones and freed-memory poisoning, and name what ASan does not find.

for a senior

Use ASan to turn a random production crash into a repeatable report, and know its blind spots, memory cost and incompatibility with ThreadSanitizer.

for a principal

Decide which test suites run under ASan and how often, given its roughly 2x slowdown and higher memory use.

## What AddressSanitizer is **AddressSanitizer (ASan)** is a memory error detector made of two parts: instrumentation that the compiler inserts around memory accesses, and a run-time library that replaces the allocator. GCC's manual describes `-fsanitize=address` as instrumenting memory access instructions "to detect out-of-bounds and use-after-free bugs", and the option also enables `-fsanitize-address-use-after-scope`. The run-time keeps **shadow memory**: a compact map that records, for each small block of application memory, whether it may be accessed. The allocator surrounds each heap object with poisoned **redzones** and keeps freed blocks poisoned for a while, so an access past the end of an object or into freed memory hits a poisoned byte and is reported at once. ## Building with it 1. Compile **and link** with `-fsanitize=address`; the GCC driver then links `libasan` (`-static-libasan` links it statically). 2. Add `-g`, which the manual recommends "to produce more meaningful output". 3. For accurate stacks, the manual suggests `-O0`, `-O1` or `-Og` and notes that `-fno-omit-frame-pointer` "also improves stack traces". 4. Run the program normally; tune the run time with the `ASAN_OPTIONS` environment variable (`help=1` lists the options). ```bash g++ -std=c++23 -g -O1 -fno-omit-frame-pointer -fsanitize=address server.cpp -o server ``` ## Reading a report The example below closes a session, erases its pointer from the vector, and then reads through a stale copy of the pointer. The report has a fixed shape: - **The headline**: the bug kind (`heap-use-after-free`) and the address. - **The access**: `READ of size 4`, which thread, and its stack. Frame `#0` here is `main` at line 14, the stale read. - **The object**: where the address lies relative to the region, "0 bytes inside of 4-byte region". - **freed by thread ... here**: the stack of the `delete`, line 11. - **previously allocated by thread ... here**: the stack of the `new`, line 8. - **SUMMARY**: one line naming the kind, file and function, convenient for log searches. - **Shadow bytes**: a dump of the shadow map around the address, rarely needed when the stacks are clear. Read each stack from the top until you reach the first frame in your own code. Those three frames answer the three questions: who used it, who freed it, who created it. ## What it finds, and what it does not | Bug | Found by ASan? | |---|---| | Heap, stack or global out-of-bounds access | yes | | Use-after-free, double free, invalid free | yes | | Use-after-scope | yes; enabled with `-fsanitize=address` in GCC | | Memory leaks | through LeakSanitizer; Clang's docs say on by default on Linux | | Data races | no; that is ThreadSanitizer | | Signed overflow, bad shifts | no; that is UndefinedBehaviorSanitizer | | Reads of uninitialized memory | no; MemorySanitizer, which Clang offers and GCC does not | ASan only catches accesses that **land on poisoned memory**. An index far enough past an array to land inside another live object, or a freed block that has already been handed out again, can go unreported. ## Cost and limits - Clang's documentation gives a typical slowdown of about **2x**, more memory than a native run, and up to 3x stack use. - It maps a very large range of virtual address space, so tools like `ulimit` may not work as expected. - GCC's manual says it **cannot be combined** with `-fsanitize=thread` or `-fsanitize=hwaddress`. - By default ASan stops at the first error: the run-time's `halt_on_error` defaults to 1 for it. Because the program behaves differently under instrumentation, a bug that crashes the production build at random may show up as a precise, repeatable report under ASan, which is exactly what makes it worth running in tests.

  • Why can ASan miss an out-of-bounds read?
    It reports only accesses that hit poisoned shadow memory. An index that jumps past the redzone into another live object reads valid-looking memory, and a freed block that has already been reused is no longer poisoned. ASan is very good evidence when it fires; silence is weaker evidence.
  • Why build the ASan job at -O1 with frame pointers instead of -O2?
    The GCC manual suggests -O0, -O1 or -Og to keep functions from being inlined and -fno-omit-frame-pointer for better stack traces. Heavier optimization merges and inlines frames, so the report's stacks are harder to map back to the source line that matters.

  • ASan finds data races between threads
  • Compiling with -fsanitize=address is enough; the link does not need it
  • ASan has no measurable cost, so it can stay on in production
  • No ASan report proves the program has no memory errors
  • ASan detects reads of uninitialized memory in GCC builds
open as a page

With GCC, what does -fsanitize=undefined check, and why can a CI job pass despite UBSan reports unless you add -fno-sanitize-recover?

level: middleimportance: should knowfreq 52%

basics

~20 s

-fsanitize=undefined inserts run-time checks for undefined operations such as signed overflow, bad shifts, division by zero and null or misaligned access. GCC enables recovery by default, so the program continues and may exit 0; -fno-sanitize-recover=undefined makes errors fatal.

open as a page

With GCC 16, what do -fhardened, _FORTIFY_SOURCE, _GLIBCXX_ASSERTIONS and -fstack-protector-strong add to a production C++ build?

level: seniorimportance: should knowfreq 38%

basics

~20 s

They are low-cost protections meant to ship, unlike sanitizers: bounds-checked string and memory calls, library precondition assertions, stack canaries. -fhardened (GCC 14+, GNU/Linux) enables them plus zeroed locals, PIE, RELRO and stack-clash protection. _FORTIFY_SOURCE only takes effect when optimizing.

open as a page

A multithreaded C++ server crashes only under load; how do you use GCC's sanitizers to find the cause, and why need two separate builds?

level: seniorimportance: should knowfreq 50%

basics

~10 s

Build two instrumented binaries and replay the load against each: -fsanitize=address,undefined for memory errors, -fsanitize=thread for data races. GCC rejects -fsanitize=thread together with address or leak, so one build cannot run both.

open as a page

How would you design the CI sanitizer matrix for a large multithreaded C++ server built with GCC, and what does each job cost?

level: principalimportance: should knowfreq 38%

basics

~20 s

Separate jobs, because thread cannot share a build with address or leak: ASan with UBSan and leak checks on every change, TSan on the concurrency tests, a hardened release build, all failing on the first report. Run the slow suites nightly.

open as a page