Kika's
Blog
图片简介 | CC BY 4.0 | 换一张

Sanitizers 一种类似Valgrind的调试工具

2023-08-23

介绍

之前一直用Valgrind这个工具来定位C/C++程序的各种内存问题,结果发现还有这个由Google开发的调试工具Sanitizers,提供更全面的报错和更好的性能(Valgrind会导致程序减慢大概20到50倍,而Sanitizers只会减慢大概2到4倍)

Sanitizers能够覆盖到如下这些Valgrind不能检测到的问题:

  1. Out-of-bounds access in stack variables
  2. Out-of-bounds access in global variables
  3. Stack use after return
  4. Undefined behavior
  5. Memory leaks with specific libraries (glib2)

但同时也有一些缺点:

  1. 没有加编译选项的library需要加上-fsanitize=address重新编译,否则Sanitizers无法检测到错误
  2. 对Uninitialized memory reads的检测时,使用Sanitizers的MemorySanitizer工具,但此时AddressSanitizer不能同时使用

Sanitizers由很多子工具组成,下面是其中几个,通过添加到GCC/CLang的编译、链接选项即可开启使用。

AddressSanitizer

能够检测以下问题:

  • Use after free (dangling pointer dereference)
  • Heap buffer overflow
  • Stack buffer overflow
  • Global buffer overflow
  • Use after return
  • Use after scope
  • Initialization order bugs
  • Memory leaks

通过添加-fsanitize=address编译、链接选项使用此工具。-fno-omit-frame-pointer获得更好的堆栈跟踪。

ThreadSanitizer

A data race detector for C/C++. A data race occurs when two threads access the same variable concurrently and at least one of the accesses is write. C++11 standard officially bans data races as undefined behavior.

通过-fsanitize=thread编译、链接选项使用此工具。

MemorySanitizer

MemorySanitizer (MSan) is a detector of uninitialized memory reads in C/C++ programs.

属于LLVM的一部分,通过添加-fsanitize=memory -fPIE -pie编译、链接选项使用此工具。

参考