程序中发生内存相关的问题,向来都是让人头大的。这里介绍一下ASan相关的内容,希望可以对debug内存相关的问题有所帮助。
ASan相关的简介可以参考wiki:https://en.wikipedia.org/wiki/AddressSanitizer
ASan在clang(3.1之后)和gcc(4.8之后)均支持,以下以gcc举例:
int main(int argc ,char **argv)
{
int stack_array[100];
stack_array[1] = 100;
return stack_array[argc + 100];
}
g++ -g -fsanitize=address main.cpp
编译好后,运行
./a.out
=================================================================
==7163==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7fff9666ccd4 at pc 0x000000400906 bp 0x7fff9666cb00 sp 0x7fff9666caf0
READ of size 4 at 0x7fff9666ccd4 thread T0
#0 0x400905 in main /home/tsing/asan/main.cpp:5
#1 0x7f199d0e982f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
#2 0x400748 in _start (/home/tsing/asan/a.out+0x400748)
Address 0x7fff9666ccd4 is located in stack of thread T0 at offset 436 in frame
#0 0x400825 in main /home/tsing/asan/main.cpp:2
This frame has 1 object(s):
[32, 432) 'stack_array' <== Memory access at offset 436 overflows this variable
HINT: this may be a false positive if your program uses some custom stack unwind mechanism or swapcontext
(longjmp and C++ exceptions *are* supported)
SUMMARY: AddressSanitizer: stack-buffer-overflow /home/tsing/asan/main.cpp:5 main
Shadow bytes around the buggy address:
0x100072cc5940: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x100072cc5950: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x100072cc5960: 00 00 00 00 f1 f1 f1 f1 00 00 00 00 00 00 00 00
0x100072cc5970: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x100072cc5980: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x100072cc5990: 00 00 00 00 00 00 00 00 00 00[f4]f4 f3 f3 f3 f3
0x100072cc59a0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x100072cc59b0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x100072cc59c0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x100072cc59d0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x100072cc59e0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
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
Container overflow: fc
Array cookie: ac
Intra object redzone: bb
ASan internal: fe
==7163==ABORTING
运行程序,会把越界访问地方的call stack打印出来。
gcc -fsanitize选项真的非常强大,heap区动态申请的内存、全局data段的内存,均可以被侦测到。另外-fsanitize选项较多,具体可以参考gcc的手册:
https://gcc.gnu.org/onlinedocs/
强烈建议备一份。这些选项包括内存泄漏的检测,多线程临界资源监测等等。