1. 程式人生 > 其它 >valgrind報的幾種記憶體洩露(轉)

valgrind報的幾種記憶體洩露(轉)

valgrind

valgrind是linux下用於除錯程式和查詢記憶體洩露的常用工具。valgrind會報告5種記憶體洩露,”definitely lost”, “indirectly lost”, “possibly lost”, “still reachable”, and “suppressed”。筆者於工作閒暇之餘對這5種(其實是4種,有一種沒研究出結果)記憶體洩露的出現原因及區別進行了研究,撰此文以記之。

測試環境:
Linux 2.6.18-194.el5 x86_64
valgrind-3.5.0

官方解釋及分析:
摘自http://valgrind.org/docs/manual/faq.html#faq.deflost5.2.With Memcheck’s memory leak detector, what’s the difference between “definitely lost”, “indirectly lost”, “possibly lost”, “still reachable”, and “suppressed”?
The details are in the Memcheck section of the user manual.
In short:

“definitely lost” means your program is leaking memory – fix those leaks!

“indirectly lost” means your program is leaking memory in a pointer-based structure. (E.g. if the root node of a binary tree is “definitely lost”, all the children will be “indirectly lost”.) If you fix the “definitely lost” leaks, the “indirectly lost” leaks should go away.

“possibly lost” means your program is leaking memory, unless you’re doing unusual things with pointers that could cause them to point into the middle of an allocated block; see the user manual for some possible causes. Use –show-possibly-lost=no if you don’t want to see these reports.

“still reachable” means your program is probably ok – it didn’t free some memory it could have. This is quite common and often reasonable. Don’t use –show-reachable=yes if you don’t want to see these reports.

“suppressed” means that a leak error has been suppressed. There are some suppressions in the default suppression files. You can ignore suppressed errors.

“definitely lost”:確認丟失。程式中存在記憶體洩露,應儘快修復。當程式結束時如果一塊動態分配的記憶體沒有被釋放且通過程式內的指標變數均無法訪問這塊記憶體則會報這個錯誤。

“indirectly lost”:間接丟失。當使用了含有指標成員的類或結構時可能會報這個錯誤。這類錯誤無需直接修復,他們總是與”definitely lost”一起出現,只要修復”definitely lost”即可。例子可參考我的例程。

“possibly lost”:可能丟失。大多數情況下應視為與”definitely lost”一樣需要儘快修復,除非你的程式讓一個指標指向一塊動態分配的記憶體(但不是這塊記憶體起始地址),然後通過運算得到這塊記憶體起始地址,再釋放它。例子可參考我的例程。當程式結束時如果一塊動態分配的記憶體沒有被釋放且通過程式內的指標變數均無法訪問這塊記憶體的起始地址,但可以訪問其中的某一部分資料,則會報這個錯誤。

“still reachable”:可以訪問,未丟失但也未釋放。如果程式是正常結束的,那麼它可能不會造成程式崩潰,但長時間執行有可能耗盡系統資源,因此筆者建議修復它。如果程式是崩潰(如訪問非法的地址而崩潰)而非正常結束的,則應當暫時忽略它,先修復導致程式崩潰的錯誤,然後重新檢測。
“suppressed”:已被解決。出現了記憶體洩露但系統自動處理了。可以無視這類錯誤。這類錯誤我沒能用例程觸發,看官方的解釋也不太清楚是作業系統處理的還是valgrind,也沒有遇到過。所以無視他吧~

本文參考來自(侵刪):https://blog.csdn.net/qq_35039122/article/details/52461855

同是寒窗苦讀, 怎願甘拜下風, 我可以一落千丈, 但我偏要一鳴驚人。