代碼可能存在內存泄露怎么辦?
使用valgrind
可以對代碼進行內存泄露檢測。
valgrind下載安裝
下載:https://www.valgrind.org/downloads/
安裝:
1、tar?–jxvf?valgrind-3.21.0.tar.bz2
2、cd?valgrind-3.21.0
3、./configure?--prefix=/home/xx/valgrind-3.21.0/install
4、make
5、make?install
--prefix為指定安裝路徑,可以不指定,使用默認的,即執行./configure?
內存泄露測試
測試程序test.c
:
分配40
個字節的buffer
,越界訪問buf[10]
.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>void test()
{int *buf = (int *)malloc(10*sizeof(int));buf[10] = 0x55;}int main()
{test();return 0;
}
編譯:
gcc?-g?-o?test?test.c
編譯時注意加上-g
選項
使用valgrinid
測試:
./valgrind?--leak-check=yes?./test
?結果顯示,產生錯誤的地方在test.c
的15
行main
函數中,即調用test()
函數。具體的在test.c
的第9
行,test
函數內,即buf[10] = 0x55;
語句。
根據提示信息,可知valgrind
檢測到了2個錯誤:
-
存在無效的寫入數據,即數組越界訪問
-
內存泄露,分配了
40
字節沒有釋放