Introduction to AddressSanitizer
AddressSanitizer is a memory error detection tool. It consists of a compiler instrumentation module and a runtime library and can quickly detect common memory errors. This memory detection method is first introduced in AddressSanitizer: A Fast Address Sanity Checker. Currently, mainstream compilers support AddressSanitizer. For details about AddressSanitizer, see LLVM documentation. When using the BiSheng compiler, you need to add the -fsanitize=address option. The AddressSanitizer runtime library can be linked to the final executable file and detect several common error types, as shown in the following table.
Error Type |
Description |
|---|---|
use-after-free |
An attempt is made to access the released memory on a heap. |
out-of-bounds accesses to heap, stack and globals |
The accesses to heaps, stacks, and global variables are out of bounds. |
use-after-return |
An attempt is made to access the released memory on a stack. |
use-after-scope |
The stack object usage exceeds the defined scope. |
double-free, invalid free |
The same memory is released repeatedly or an invalid memory area is released. |
memory leaks |
Memory leaks exist. |
initialization order checking |
The initialization order is checked. |
Generally, you can use -fsanitize=address to compile and link programs to enable AddressSanitizer. When the shared library is linked, the AddressSanitizer runtime is not linked. Therefore, -Wl, -z,defs may cause link errors. Adding -fno-omit-frame-pointer to disable the stack frame pointer can obtain a better call stack. Generally, enabling AddressSanitizer causes about two times of performance rollback.