#1. 用Address Sanitizer工具检查内存访问错误
除了用gdb检测内存访问错误外,集成了address sanitizer工具的gcc也可以实现这个功能。举个例如:
//test.cpp
#include <iostream>
int main() {
int a[2];
a[2] = 1;
return 0;
}
加上以下参数编译:
g++ -fsanitize=address -g test.cpp -o test
运行可执行文件test的结果如下:
其中“SUMMARY: AddressSanitizer: stack-buffer-overflow /home/ysm/Documents/test.cpp:5 main”定位出内存访问错误的代码位置。