AddressSanitizer使用简析

759 阅读1分钟

介绍

快速的内存错误检测工具(memory detector), 可以检测如下几种bug:

  1. 堆内存, 栈内存和全局变量的越界访问(out-of-bounds-access)
  2. 释放后的内存再次使用(use-after-free)
  3. 返回后使用(use-after-return)
  4. 重复释放(double-free)

编译构建

参照clang的build介绍, 不支持CMake

使用方法

只需要在编译和链接程序时,添加-faddress-sanitizer选项

要获得合理的性能, 添加-O1或更高的优化级别

要在错误信息中获得更好地堆栈追踪, 添加 -fno-omit-frame-pointer选项

为获得完美的堆栈追踪, 可能需要禁用内联(just use -O1)和尾部调用消除-fno-optimize-sibling-calls

__has_feature(address_sanitizer)

某些情况根据是否启用了AddressSanitizer决定执行不同的代码, 可以使用_has_feature达到此目的:

#if defined(__has_feature) && __has_feature(address_sanitizer)
  code that runs only under AddressSanitizer
#else
  code that does not run under AddressSanitizer
#endif

局限

AddressSanitizer比本地运行使用的实际内存更多, 取决于分配的大小

64位平台上, AddresSanitizer映射16+TB的虚拟地址空间, 这意味着像ulimit这样的工具无法正常使用

不支持静态链接

附链接地址:

ASAN的文档