现在 gcc 主干中提供了 AddressSanitizer 的 gcc 变体(很快将是 4.8)。它还没有clang版本那么成熟,但你可以试试。
% cat use-after-free.cc
#include <stdlib.h>
int main() {
char *x = (char*)malloc(10 * sizeof(char));
free(x);
return x[5];
}
% g++ --version | head -1
g++ (GCC) 4.8.0 20130216 (experimental)
% g++ -fsanitize=address -static-libasan use-after-free.cc && ./a.out 2>&1 | asan_symbolize.py
=================================================================
==9817== ERROR: AddressSanitizer: heap-use-after-free on address 0x60040000dff5 at pc 0x4179c3 bp 0x7fffe046af30 sp 0x7fffe046af28
READ of size 1 at 0x60040000dff5 thread T0
#0 0x4179c2 in main ??:0
#1 0x7f469c8dc76c in __libc_start_main /build/buildd/eglibc-2.15/csu/libc-start.c:226
#2 0x402098 in _start ??:0
0x60040000dff5 is located 5 bytes inside of 10-byte region [0x60040000dff0,0x60040000dffa)
freed by thread T0 here:
#0 0x40f18a in free ??:0
#1 0x417980 in main ??:0
#2 0x7f469c8dc76c in __libc_start_main /build/buildd/eglibc-2.15/csu/libc-start.c:226
previously allocated by thread T0 here:
#0 0x40f26a in malloc ??:0
#1 0x417970 in main ??:0
#2 0x7f469c8dc76c in __libc_start_main /build/buildd/eglibc-2.15/csu/libc-start.c:226