1. 程式人生 > >linux記憶體除錯、記憶體洩漏檢測以及效能分析的工具-valgrind

linux記憶體除錯、記憶體洩漏檢測以及效能分析的工具-valgrind

Valgrind這個名字取自北歐神話中英靈殿的入口。
Valgrind的最初作者是Julian Seward,他於2006年由於在開發Valgrind上的工作獲得了第二屆Google-O’Reilly開原始碼獎。
Valgrind遵守GNU通用公共許可證條款,是一款自由軟體。

官網連結

http://www.valgrind.org

下載與安裝

下載地址:
http://www.valgrind.org/downloads/valgrind-3.11.0.tar.bz2
安裝:

wget http://www.valgrind.org/downloads/valgrind-3.11
.0.tar.bz2 cd valgrind-3.8.1 ./configure --prefix=/usr/local/webserver/valgrind make make install

fedora 22 快速安裝方式:

dnf install -y valgrind

試用:

編譯

gcc -g -o test C.cpp

記憶體檢查

valgrind --tool=memcheck --leak-check=yes --show-reachable=yes ./C

結果

[[email protected] C]$ valgrind --tool=memcheck --leak-check=yes --show-reachable=yes ./Debug/CTMPServer20160413
==2923
== Memcheck, a memory error detector
==2923== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al. ==2923== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info ==2923== Command: ./Debug/C Read the configuration file ==2923== Mismatched free() / delete / delete [] ==2923== at 0x4A08184
: operator delete(void*) (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==2923== by 0x4054E3: readfile(int) (text.cc:156) ==2923== by 0x40E7A0: global::parseFile(char*) (global.cc:238) ==2923== by 0x40E165: global::global(char*, short, bool, char*, char*, char*) (global.cc:160) ==2923== by 0x40F345: larbin(char*, short, bool, char*, char*, char*) (larbin.cc:69) ==2923== by 0x40F6DE: main (C.cpp:25) ==2923== Address 0x68e9b50 is 0 bytes inside a block of size 512 alloc'd ==2923== by 0x40F6DE: main (C.cpp:25) ==2923== Invalid write of size 4 ==2923== at 0x406098: url::url(char*) (url.cc:219) ==2923== by 0x4032E9: PersistentFifo::tryGet() (PersistentFifo.cc:98)

說明
Invalid write of size 4:表示陣列越界寫了4位元組

文件:

下載地址
http://www.valgrind.org/docs/download_docs.html

Valgrind 中包含的 Memcheck 工具可以檢查以下的程式錯誤:

  使用未初始化的記憶體 (Use of uninitialised memory)
  使用已經釋放了的記憶體 (Reading/writing memory after it has been free’d)
  使用超過malloc分配的記憶體空間(Reading/writing off the end of malloc’d blocks)
  對堆疊的非法訪問 (Reading/writing inappropriate areas on the stack)
  申請的空間是否有釋放 (Memory leaks – where pointers to malloc’d blocks are lost forever)
  malloc/free/new/delete申請和釋放記憶體的匹配(Mismatched use of malloc/new/new [] vs free/delete/delete [])
  src和dst的重疊(Overlapping src and dst pointers in memcpy() and related functions)
  重複free
其他情況還不清楚,等待後續新增