c++内存分析:ASan
AddressSanitizer(ASan)是一款广泛使用的c++内存分析工具,能够检测代码中的各种内存问题(内存越界、访问野指针、非法访问栈内存等等很多)
唯独不能分析内存泄漏问题,内存泄漏问题可以用另外一款名为LeakSanitizer(LSan)的工具检测
vs 2022 内置了对ASan的支持,参考https://learn.microsoft.com/zh-cn/cpp/sanitizers/asan?view=msvc-170
如何在vs中配置ASan
0. 安装
使用vs installer安装ASan支持
1. Enable AddressSanitizer(ASan)
Configuration Properties > C/C++ > General, then modify the Enable AddressSanitizer property. Choose OK to save your changes.
2. 触发内存问题后生成dump
添加环境变量:set ASAN_SAVE_DUMPS=MyFileName.dmp
参考https://learn.microsoft.com/zh-cn/cpp/sanitizers/asan-debugger-integration?view=msvc-170
3. Continue on error
参考https://learn.microsoft.com/zh-cn/cpp/sanitizers/asan-continue-on-error?view=msvc-170
默认是触发了内存问题后直接抛异常然后crash,开启这个选项以后可以让程序继续执行,等程序结束后统一输出错误报告
添加环境变量:set ASAN_OPTIONS=continue_on_error=1
使用 ASAN_OPTIONS 环境变量确定将 ASAN 输出发送到何处,如下所示:
- 输出到 stdout:set ASAN_OPTIONS = continue_on_error = 1
- 输出到 stderr:set ASAN_OPTIONS = continue_on_error = 2
- 输出到所选日志文件:set COE_LOG_FILE = yourfile.log
4. 启用分配和释放不匹配检测
这个并不是检测内存泄漏,主要是检测 new/free,malloc/delete 这样的不匹配问题
默认不开启
添加环境变量:set ASAN_OPTIONS = alloc_dealloc_mismatch = 1
5. ASAN_OPTIONS的多个选项之间用冒号分隔
例如:set ASAN_OPTIONS=continue_on_error=1:alloc_dealloc_mismatch=1
Debug模式或/Od优化模式下需要的额外配置
Turn off edit and continue
Open Tools > Options > Debugging > .NET / C++ Hot Reload.
Turn off both of the following options to enable Edit and Continue. - Enable Hot Reload and Edit and Continue when debugging. - Enable Hot Reload when starting without debugging
Turn off /RTC1
Configuration Properties > C / C++ > Code Generation property page.
Turn off one or both of the following properties : Basic Runtime Checks or Smaller Type Check.
Turn off Incremental Link
Select the Configuration Properties > Linker > General property page.
Modify the Enable Incremental Linking property.
Trouble shooting
1. The code execution cannot proceed because clang_rt.asan_dynamic-x86_64.dll was not found.
Please update the PATH to include clang_rt.asan_dynamic - x86_64.dll(x64) or clang_rt.asan_dynamic - i386.dll(x86).
2. AddressSanitizer crash
更新vs到最新版本