AddressSanitizer介绍
AddressSanitizer is a fast memory error detector. It consists of a compiler instrumentation module and a run-time library. The tool can detect the following types of bugs:
- Out-of-bounds accesses to heap, stack and globals
- Use-after-free
- Use-after-return (runtime flag ASAN_OPTIONS=detect_stack_use_after_return=1)
- Use-after-scope (clang flag -fsanitize-address-use-after-scope)
- Double-free, invalid free
- Memory leaks (experimental)
使用方法
在gcc编译选项中添加:-fsanitize=address
如在CMakeLists.txt中:set(CMAKE_C_FLAGS “-Wall -Werror -fsanitize=address”)
举例
如果发生上述问题,则运行程序后,系统会主动报告问题原因和代码位置:
int main(int argc, char const **argv)
{
char *array = malloc(100);
strcpy(array, "test");
return 0;
}
程序运行后,系统会主动报告出现的问题和代码位置,如下图所示,最后一行显示上述代码发生了内存泄露,100个字节,因此可以断定是申请的array没有释放导致。
其他问题,比如内存越界,重复释放等,空指针访问,空指针释放等都可以容易定位。
https://github.com/google/sanitizers/wiki/AddressSanitizer