1. 程式人生 > >系統技術非業餘研究 » gcc mudflap 用來檢測記憶體越界的問題

系統技術非業餘研究 » gcc mudflap 用來檢測記憶體越界的問題

我們用C語言在做大型伺服器程式的時候,不可避免的要面對記憶體錯誤的問題。典型的問題是記憶體洩漏,越界,隨機亂寫等問題。 在linux下valgrind是個很好的工具,大部分問題都可以查的到的。但是對於更微妙的越界問題,valgrind有時候也是無能為力的。比如下面的問題。

[[email protected] ~]$ cat bug.c

int a[10];
int b[10];
int main(void) {
   return a[11];
}
[[email protected] ~]$ gcc -g -o bug bug.c
[[email protected]
~]$ valgrind ./bug ==5791== Memcheck, a memory error detector. ==5791== Copyright (C) 2002-2006, and GNU GPL'd, by Julian Seward et al. ==5791== Using LibVEX rev 1658, a library for dynamic binary translation. ==5791== Copyright (C) 2004-2006, and GNU GPL'd, by OpenWorks LLP. ==5791== Using valgrind-3.2.1, a dynamic binary instrumentation framework. ==5791== Copyright (C) 2000-2006, and GNU GPL'd, by Julian Seward et al. ==5791== For more details, rerun with: -v ==5791== ==5791== ==5791== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 1) ==5791== malloc/free: in use at exit: 0 bytes in 0 blocks. ==5791== malloc/free: 0 allocs, 0 frees, 0 bytes allocated. ==5791== For counts of detected errors, rerun with: -v ==5791== All heap blocks were freed -- no leaks are possible. [
[email protected]
~]$

valgrind報告一切安好。

[[email protected] ~]$ gcc -o bug bug.c -g -fmudflap -lmudflap
[[email protected] ~]$ ./bug
*******
mudflap violation 1 (check/read): time=1285386334.204054 ptr=0x700e00 size=48
pc=0x2b6c3013c4c1 location=`bug.c:5 (main)'
      /usr/lib64/libmudflap.so.0(__mf_check+0x41) [0x2b6c3013c4c1]
      ./bug(main+0x7a) [0x400952]
      /lib64/libc.so.6(__libc_start_main+0xf4) [0x39ea21d994]
Nearby object 1: checked region begins 0B into and ends 8B after
mudflap object 0x16599370: name=`bug.c:1 a'
bounds=[0x700e00,0x700e27] size=40 area=static check=3r/0w liveness=3
alloc time=1285386334.204025 pc=0x2b6c3013bfe1
number of nearby objects: 1

mudflap就很順利的檢查出來了。

[[email protected] ~]$ gcc -v

gcc version 4.1.2 20080704 (Red Hat 4.1.2-46)

當然我們的這個例子很簡單,典型的伺服器要比這個複雜很多, 而且mudflap的執行開銷也非常高,我們在定位此類bug的時候不妨實驗下。
Have fun!

Post Footer automatically generated by wp-posturl plugin for wordpress.

No related posts.