@
zhicheng 如果有用gcc 4.9的话, 建议编译时候带上address-sanitizer,这类问题很容易查出。
比如 假设源文件是 test.c, 那么用gcc -o test test.c -fsanitize=address 编译成test,然后运行./test。
输出结果是 heap-buffer-overflow 堆区域overflow,如下:
SUMMARY: AddressSanitizer: heap-buffer-overflow ??:0 wrap_strlen
Shadow bytes around the buggy address:
0x1c24000017a0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x1c24000017b0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x1c24000017c0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x1c24000017d0: fa fa fa fa fa fa fa fa 00 00 00 00 00 00 00 00
0x1c24000017e0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x1c24000017f0: 00 00 00 00 00 00 00 00 00[fa]fa fa fa fa fa fa
0x1c2400001800: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x1c2400001810: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x1c2400001820: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x1c2400001830: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x1c2400001840: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
Addressable: 00
Partially addressable: 01 02 03 04 05 06 07
Heap left redzone: fa
Heap right redzone: fb
Freed heap region: fd
Stack left redzone: f1
Stack mid redzone: f2
Stack right redzone: f3
Stack partial redzone: f4
Stack after return: f5
Stack use after scope: f8
Global redzone: f9
Global init order: f6
Poisoned by user: f7
Contiguous container OOB:fc
ASan internal: fe
==43896==ABORTING
Abort trap: 6
如果没有高版本的gcc (至少4.8),或者clang,那用valgrind 也是可行的。