To integrate AddressSanitizer(ASan) to an existing project, just add the compile option -fsanitize=address
and generate debug infor with -g
in CMakeLists.txt
.
option(ENABLE_ASAN "enable AddressSanitizer" OFF)
if(ENABLE_ASAN)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address")
set(CMAKE_CXX_FLAGS "-O -g")
set(CMAKE_C_FLAGS "-O -g")
endif()
Compile the project:
mkdir build
cd build
cmake -DENABLE_ASAN=ON ..
cmake --build .
After the build, using following command to start the program:
ASAN_OPTIONS=detect_leaks=1 ./a.out
It will print detail info when memory leak occurs.
=================================================================
==12345==ERROR: LeakSanitizer: detected memory leaks
Direct leak of 40 byte(s) in 1 object(s) allocated from:
#0 0x7f3d8b4fbb90 in __interceptor_new (/usr/lib/x86_64-linux-gnu/libasan.so.4+0xde90)
#1 0x4006d6 in createLeak /path/to/your/project/main.cpp:4
#2 0x4006f8 in main /path/to/your/project/main.cpp:9
#3 0x7f3d8b0d283f in __libc_start_main (/lib64/libc.so.6+0x2383f)
SUMMARY: AddressSanitizer: 40 byte(s) leaked in 1 allocation(s).