Summary
In this post, I will introduce a useful tool called AddressSanitizer. The motivation of it is that I have a debate with one of my colleagues about whether it is necessary to detect memory leaks in small projects. I was the one who persists to avoid memory issues though the program is small and terminates after a single usage. I did some research on AddressSanitizer thanks to the debate.
Conclusion
C/C++ is fast. It does not have garbage collection and programmers need to explicitly manage memories.
To keep your programs safe, compile and link your program using clang
or gcc
with the -fsanitize=address
switch. To get nicer stack traces in error messages add -fno-omit-frame-pointer
. To get reasonable performance, add -O1
or higher.
It detects:
- Use after free (dangling pointer dereference)
- Heap buffer overflow (out of boundary)
- Stack buffer overflow
- Global buffer overflow
- Use after return
- Use after scope
- Initialization order bugs
- Memory leaks
Details
The project AddressSanitizer is a very popular open-source project. The followings are some facts about it:
- Popularity: Google develops and maintains it. The project has 4.5k stars and 300+ forks. AddressSanitizer is currently implemented in both Clang and GCC. It is part of Linux kernel as well.
- Correctness: The project has a paper with nearly 500 citings to support it. ; the tool has no false positives.
- Users: Chromium and Firefox, the two most famous open-source browsers, are using AddressSanitizer.
- Overhead: The average slowdown of the instrumented program is
~2x
. The increased memory usage is~4x
.