Memory bugs in C and C++ often do not crash at the point of the error. A use-after-free can corrupt data and crash much later in unrelated code. AddressSanitizer (ASan) is a compiler-based tool that detects these bugs at the faulting memory access. GCC and Clang both support it. This post shows how to enable ASan, read its report, and use it with GDB.
Advantages of ASan
| Advantage | Description |
|---|---|
| Early detection | ASan reports the first invalid memory access when it occurs. |
| Detailed report | The report shows the error type, the address, and the stack traces of the access, allocation, and free. |
| Low overhead | A typical slowdown is about 2x. This is much faster than tools such as Valgrind, so you can run full test suites with it. |
Memory errors that ASan detects
- Use after free (dangling pointer dereference)
- Heap buffer overflow
- Stack buffer overflow
- Global buffer overflow
- Use after return
- Use after scope
- Initialization order bugs
- Memory leaks
How ASan works
- Instrumentation: At compile time, the compiler instruments each memory access with a check.
- Shadow memory: ASan maps application memory to shadow memory. Each shadow byte records whether 8 bytes of application memory are addressable.
- Runtime check: On each load or store, the instrumented code checks the shadow memory. If the address is poisoned, ASan reports the error and terminates the program.
- Error report: ASan prints the error type, the memory address, and the stack traces.
How to use ASan
To enable ASan, compile and link with the -fsanitize=address flag.
$ gcc -o my_program -fsanitize=address my_program.c
Then run the program. If ASan finds a memory error, it prints a report and exits.
Use-after-free example
This program reads from a heap buffer after it frees the buffer.
#include <stdlib.h>
int main() {
char *x = (char*)malloc(10 * sizeof(char*));
free(x);
return x[5];
}Compile it with -fsanitize=address. Add -fno-omit-frame-pointer to get better stack traces.
$ gcc use-after-free.c -fsanitize=address -fno-omit-frame-pointer
Result
The report shows a heap-use-after-free error, the faulting address, and the stack traces where the memory was allocated and freed.

Using ASan with GDB
You can debug an ASan-instrumented binary with GDB as usual. When ASan finds a bug, it calls one of the __asan_report_{load,store}{1,2,4,8,16} functions. These functions then call __asan::ReportGenericError.
| When to stop | Method |
|---|---|
| Before ASan prints the report | Set a breakpoint on __asan::ReportGenericError. |
| After ASan prints the report | Set a breakpoint on __sanitizer::Die, or run the binary with ASAN_OPTIONS=abort_on_error=1. |
In GDB, you can ask ASan to describe a memory address.
(gdb) set overload-resolution off
(gdb) p __asan_describe_address(0x7ffff73c3f80)
0x7ffff73c3f80 is located 0 bytes inside of 10-byte region [0x7ffff73c3f80,0x7ffff73c3f8a)
freed by thread T0 here:
...