CSE Roadmap

Core tier · about 5 hours · 7 parts

Part 4 of 7 · 2 min read

AddressSanitizer

In plain words: AddressSanitizer (ASan) is a tool built into gcc and clang. A program is compiled with -fsanitize=address (and -g for line numbers). The compiler then adds a check before each load and store, and the runtime replaces malloc and free with versions that surround each block with red zones, extra bytes that are marked as forbidden. A side table, called shadow memory, records for every 8 bytes whether the access is allowed. A freed block is also marked forbidden, and is kept out of use for a while, so that a late access to it is caught.

gcc -g -O0 -fsanitize=address -o bugs_asan bugs.c
./bugs_asan 1

The reports on the five cases of section 1, shortened to the lines that matter:

Case First line of the ASan report
1, overflow ERROR: AddressSanitizer: heap-buffer-overflow with "WRITE of size 1", "0 bytes after 16-byte region", and the line bugs.c:9
2, use after free heap-use-after-free, "READ of size 1", the line of the read and the lines of the free and of the allocation
3, double free attempting double-free with the line of the first free and of the allocation
4, leak LeakSanitizer: detected memory leaks, "16 byte(s) leaked in 1 allocation(s)"
5, uninitialised read not reported (ASan does not track that)

Each report names the kind of bug, the access, the offset from the block, and the call stacks of the allocation and of any free. The one-byte overflow that the plain run did not notice is found at the first wrong byte. The program stops at the first error by default.

The price is time and memory. On a small test loop that sums a 4 MiB array 50 times, the plain build took 0.024 s and the ASan build 0.058 s, about 2.4 times longer. The red zones and the delayed reuse of freed blocks raise memory use too. For this reason ASan is a tool for testing, not for the production build of a program.

AddressSanitizer

AddressSanitizer (ASan) is a compiler feature that checks every memory access of a program against a table of allowed bytes, with forbidden red zones around heap blocks and around freed blocks, and stops with a report at the first illegal access.

Example: a write one byte past a 16-byte block hits a red zone, and ASan reports a heap-buffer-overflow with the line of the write.

Check yourself: 1. What does the -fsanitize=address option change in the program? 2. Why does ASan find an overflow that a plain run misses? 3. Which of the five cases did ASan not report?