Debugging & Tooling

AddressSanitizer (ASan)

/ ASan -> AY-san /

Imagine if, instead of running your program inside a slow simulator after the fact, the compiler itself wired a tiny burglar alarm into every memory access while building your program - so the moment you touch memory you should not, an alarm fires and tells you exactly where. AddressSanitizer is that built-in alarm. You add one flag when compiling, and your program now detects memory errors as it runs, at close to normal speed, crashing loudly with a precise report the instant something goes wrong.

Concretely, ASan is a sanitizer built into gcc and clang. You compile with -fsanitize=address (typically alongside -g for line numbers), and the compiler instruments the code: it surrounds every heap and stack allocation with poisoned 'redzones' and keeps a shadow map recording which bytes are valid to access. Every load and store is checked against that shadow. If your code reads or writes into a redzone (a buffer overflow), touches memory after it was freed (use-after-free), uses a stack variable after its function returned (stack-use-after-return), or frees twice, ASan stops immediately and prints a detailed report: the kind of error, the faulting address, and stack traces for the bad access, the allocation, and the free. The cost is modest - roughly 2x slower and more memory - because the checks are compiled in rather than interpreted.

Why it matters: ASan catches the most dangerous C bugs - overflows and use-after-free that otherwise corrupt memory silently and crash much later - and it is fast enough to leave on during your whole test suite, so bugs are caught the first time a bad access happens rather than via a delayed mysterious crash. Honest caveats: it must be compiled in, so it only checks the code you built with it (not third-party binaries); it finds errors only on paths your tests actually execute; it does not by default catch uninitialized reads (that is MemorySanitizer) or data races (ThreadSanitizer), and you cannot combine ASan and TSan in one build. It is the modern first reach for memory-corruption bugs, complementing Valgrind with far less slowdown.

$ gcc -g -fsanitize=address overflow.c -o a then $ ./a on code that writes arr[10] into a 10-element array prints 'ERROR: AddressSanitizer: stack-buffer-overflow ... WRITE of size 4 at ... in main overflow.c:8' and aborts immediately - no delayed mystery crash.

Compile with -fsanitize=address; the bad write is reported at the exact line, instantly.

ASan only instruments code you compiled with it and only catches errors on paths your run actually takes - a clean ASan run means 'no error on these inputs', not 'provably bug-free'. It does not detect uninitialized reads or data races, and ASan and ThreadSanitizer cannot be enabled together.

Also called
ASan-fsanitize=addressaddress sanitizer