1. 程式人生 > >Linux C/C++ 記憶體洩漏檢測工具Valgrind

Linux C/C++ 記憶體洩漏檢測工具Valgrind

下面是一段有問題的C程式程式碼test.c

#i nclude <stdlib.h>
void f(void)
{
   int* x = malloc(10 * sizeof(int));
   x[10] = 0;  //問題1: 陣列下標越界
}                  //問題2: 記憶體沒有釋放
int main(void)
{
   f();
   return 0;
 }
1、 編譯程式test.c
gcc -Wall test.c -g -o test
2、 使用Valgrind檢查程式BUG
valgrind --tool=memcheck --leak-check=full ./test
3、 分析輸出的除錯資訊
==3908== Memcheck, a memory error detector.
==3908== Copyright (C) 2002-2007, and GNU GPL'd, by Julian Seward et al.
==3908== Using LibVEX rev 1732, a library for dynamic binary translation.
==3908== Copyright (C) 2004-2007, and GNU GPL'd, by OpenWorks LLP.
==3908== Using valgrind
-3.2.3, a dynamic binary instrumentation framework. ==3908== Copyright (C) 2000-2007, and GNU GPL'd, by Julian Seward et al. ==3908== For more details, rerun with: -v ==3908== --3908-- DWARF2 CFI reader: unhandled CFI instruction 0:50 --3908-- DWARF2 CFI reader: unhandled CFI instruction 0:50 /*陣列越界錯誤*/ ==3908== Invalid write of size 4 ==3908== at 0x8048384: f (test.c:6) ==3908== by 0x80483AC: main (test.c:11) ==3908== Address 0x400C050 is 0 bytes after a block of size 40 alloc'd ==3908== at 0x40046F2: malloc (vg_replace_malloc.c:149) ==3908== by 0x8048377: f (test.c:5) ==3908== by 0x80483AC: main (test.c:11) ==3908== ==3908== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 14 from 1) ==3908== malloc/free: in use at exit: 40 bytes in 1 blocks. ==3908== malloc/free: 1 allocs, 0 frees, 40 bytes allocated. ==3908== For counts of detected errors, rerun with: -v ==3908== searching for pointers to 1 not-freed blocks. ==3908== checked 59,124 bytes. ==3908== ==3908== /*有記憶體空間沒有釋放*/ ==3908== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1 ==3908== at 0x40046F2: malloc (vg_replace_malloc.c:149) ==3908== by 0x8048377: f (test.c:5) ==3908== by 0x80483AC: main (test.c:11) ==3908== ==3908== LEAK SUMMARY: ==3908== definitely lost: 40 bytes in 1 blocks. ==3908== possibly lost: 0 bytes in 0 blocks. ==3908== still reachable: 0 bytes in 0 blocks. ==3908== suppressed: 0 bytes in 0 blocks.