1

我正在尝试使用 ( -fsanitize=address) 来使用地址清理程序,但我不确定它是否属于 CFLAGS 或 LDFLAGS。仅将其添加到 LDFLAGS 时,它实际上似乎工作正常,但我不知道这是巧合还是应该是这样。

-fsanitize=address编译本身需要,还是为链接步骤提供标志就足够了?

4

1 回答 1

3

编译本身是否需要 -fsanitize=address,还是为链接步骤提供标志就足够了?

地址 Sanitizer 工具源代码以插入额外的检查,因此在编译时必须存在。

仅在链接行上提供参数会导致运行时链接到进程中,但实际上不会进行任何检查,除了一小部分 - 即通过插入new deletemallocfree和其他标准函数可实现的检查。

例子:

     1  #include <malloc.h>
     2  #include <stdio.h>
     3
     4  void fn(int *ip)
     5  {
     6    ip[0] = 1;  // BUG: heap buffer overflow
     7  }
     8
     9  int main()
    10  {
    11    int *ip = malloc(1);   // Allocation too small.
    12    printf("%d\n", ip[0]); // BUG: heap buffer overflow
    13    free(ip);
    14    free(ip);  // BUG: double free
    15  }

在没有仪器的情况下,仅检测到双自由:

gcc -g -c t.c && gcc -fsanitize=address t.o && ./a.out
190
=================================================================
==55787==ERROR: AddressSanitizer: attempting double-free on 0x602000000010 in thread T0:

使用检测:同时检测到错误printf和错误fn

gcc -g -c -fsanitize=address t.c && gcc -fsanitize=address t.o && ./a.out
=================================================================
==58202==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000010 at pc 0x564565639252 bp 0x7ffe36b0a560 sp 0x7ffe36b0a558
READ of size 4 at 0x602000000010 thread T0
    #0 0x564565639251 in main /tmp/t.c:12
于 2020-03-28T15:20:42.947 回答