AddressSanitizer+cmake

这篇博客介绍了如何使用AddressSanitizer(ASan),一个高效的内存错误检测工具,进行内存泄漏检测。在Linux环境下,通过CMake和特定的编译标志 `-fsanitize=address`,`-fno-omit-frame-pointer` 和 `-fsanitize-recover=address` 来启用ASan。运行时,通过设置环境变量 `ASAN_OPTIONS` 控制错误处理行为,并使用 `LD_PRELOAD` 链接ASan库。博客还提及了ASan的安装方法,以及在Ubuntu和CentOS上的安装命令。示例代码展示了一个导致内存泄漏的情况,并演示了ASan如何报告泄漏。最后,博客提供了关于ASan的更多信息来源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. AddressSanitizer+cmake(Linux)

编译指令:
CXXFLAGS通常需要加上

-fsanitize=address
-fno-omit-frame-pointer     #打印函数调用路径
-fsanitize-recover=address  #AddressSanitizer遇到错误时能够继续
-fsanitize=address

-fno-omit-frame-pointer

-fsanitize-recover=address

### 2. 运行时动态链接
设置环境变量,如设置AddressSanitizer遇到错误时继续运行

export ASAN_OPTIONS="halt_on_error=0:abort_on_error=0"

链接ASAN库

LD_PRELOAD=xxxxx/libasan.so ./out
sun@sun:~/nolo/asan_test$ g++ asan_test.cpp -o main -fsanitize=leak
sun@sun:~/nolo/asan_test$ ls
asan_test.cpp  main
sun@sun:~/nolo/asan_test$ ./main 

=================================================================
==184528==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 40 byte(s) in 1 object(s) allocated from:
    #0 0x7fa1c10cc501 in operator new[](unsigned long) ../../../../src/libsanitizer/lsan/lsan_interceptors.cpp:231
    #1 0x5595b681319e in main (/home/sun/nolo/asan_test/main+0x119e)
    #2 0x7fa1c0ba50b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)

SUMMARY: LeakSanitizer: 40 byte(s) leaked in 1 allocation(s).
sun@sun:~/nolo/asan_test$ cat asan_test.cpp 
#include <iostream>

int main()
{
int* p = new int[10];
p = NULL;
return 0;
}

3. 安装

AddressSanitizer(地址杀菌剂,简称 ASan) 是谷歌出品的内存检查工具,比 Valgrind 更高效。其由两部组成:

编译器 instrumentation 模块
提供malloc()/free()替代项的运行时库
gcc 4.8 开始,AddressSanitizer 成为 gcc 的一部分,但不支持符号信息,无法显示出问题的函数和行数。从 4.9 开始,gcc 支持 AddressSanitizer 的所有功能。

Ubuntu 一般不用安装,CentOS 一般需要安装。

如果使用 AddressSanitizer 时报错:

/usr/bin/ld: cannot find /usr/lib64/libasan.so.0.0.0
则需要先安装。Ubuntu 安装命令:

sudo apt-get install libasan0
CentOS 安装命令:

sudo yum install libasan
使用
在用 gcc 编译程序时,指定 -fsanitize=address 选项即可自动调用 AddressSanitizer。运行程序时,就可以看到相关信息。

通过 -g 选项,可以看到报错的函数和行号。

3. 参考

博客园:https://www.cnblogs.com/kika/p/10851494.html
Github 地址:https://github.com/google/sanitizers
Wiki 地址:https://github.com/google/sanitizers/wiki/AddressSanitizer
基本使用:https://blog.csdn.net/c_lazy/article/details/80009627
输出信息的详细解释:https://www.jianshu.com/p/3a2df9b7c353

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大江东去浪淘尽千古风流人物

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值