AddressSanitizer (ASan) 是一种编译器和执行时间技术,会以 零 误报来公开许多难以发现的 bug:
配置/dealloc 不符和delete 类型不符配置太大而无法堆积溢位和 溢位免费且免费使用全域变数溢位堆积缓冲区溢位对齐的值对齐无效memcpy和memcpy堆叠缓冲区溢 位和 下溢堆叠使用 并在範围后使用有害之后的记忆体使用量安装 AddressSanitizer
从 Visual Studio 2019 16.9 版开始,Microsoft C/c + + 编译器 (MSVC) 和 IDE 支援AddressSanitizer
开启Visual studio installer
更新或确认Visual studio版本


使用 Visual Studio 中的 AddressSanitizer
先根据官网提供的source code建立一个CPP档案
// basic-global-overflow.cpp#include <stdio.h>int x[100];int main() { #ifdef __SANITIZE_ADDRESS__ printf("Address sanitizer enabled\n"); #else printf("Address sanitizer not enabled\n"); #endif printf("Hello!\n"); x[100] = 5; // Boom! return 0;}
设定ASan
专案属性 → C/C++ → 一般 → 启用[ASan] 选择是
MSVS的 AddressSanitizer 已知问题 有开启ASan还需进行一些设定,才能正常使用
我的环境需要将 侦错资讯格式 设定成 无,才可以正常使用
测试範例
F5执行后显示错误讯息
0x007a9350 is located 0 bytes to the right of global variable 'x' defined in 'main.cpp:3:4' (0x7a91c0) of size 400
这边显示显示错误的地方
#0 0x7a1081 in main+0x61 (D:\temp\stdThreadPrj\Debug\stdThreadPrj.exe+0x401081)
这个部分可以参考 使用visual studio trace call stack的private function 来找到错误的位置
reference
[1] AddressSanitizer | Microsoft Docs