使用AddressSanitizer做内存分析(一)——入门篇
使用AddressSanitizer做内存分析
新建文件mem_leak.cpp,键入代码:
#include <iostream> int main() { int* p = new int[10]; p = NULL; return 0; }
编译时加上-fsanitizer=leak选项,并执行:
$ g++ mem.leak.cpp -o main -fsanitize=leak $ ./main
./main: error while loading shared libraries: liblsan.so.0: cannot open shared object file: No such file or directory
发现报错,找不到liblsan.so。
全局查找liblsan.so:
$ sudo find / -name liblsan.so.0 /usr/local/lib/liblsan.so.0 /usr/local/lib64/liblsan.so.0 /usr/lib/liblsan.so.0 /root/open_source/gcc-build-5.1.0/x86_64-unknown-linux-gnu/libsanitizer/lsan/.libs/liblsan.so.0
发现其实是能找到的,只是不在系统默认目录下,这个时候可以采用如下方法:
$ su Password: # sudo echo "/user/local/lib64" >> /etc/ld.so.conf
# ldconfig
将 "/user/local/lib64" 追加到 /etc/ld.so.conf 后,echo命令需要root权限,也可以用 sudo vim,直接在 /etc/ld.so.conf 后面添加。
此时再执行之前编译好的可执行文件,即可查看结果:
$ ./main ================================================================= ==20779==ERROR: LeakSanitizer: detected memory leaks Direct leak of 40 byte(s) in 1 object(s) allocated from: #0 0x7f3deb1ac816 in operator new[](unsigned long) ../../../../gcc-5.1.0/libsanitizer/lsan/lsan_interceptors.cc:154 #1 0x4007f7 in main (/home/minglee/workspace/test_code/mem_leak/main+0x4007f7) #2 0x7f3dea56bc04 in __libc_start_main (/lib64/libc.so.6+0x21c04) SUMMARY: LeakSanitizer: 40 byte(s) leaked in 1 allocation(s).