有人能夠闡明爲什麼Valgrind將此程序歸類爲「絕對丟失:2個字節的1塊」內存泄漏?我瞭解評論線可以解決問題,但我不瞭解分類。根據Valgrind文檔,內存泄漏應該被分類爲「間接可達」。我也很好奇,爲什麼這甚至被認爲是內存泄漏,並會讚賞解釋。即使程序在main
函數的末尾終止,是否手動釋放所有內容是一種好的做法?在C程序中肯定會失去內存泄漏
#include <stdlib.h>
struct wrapper {
char *data;
};
char *strdup(const char *);
struct wrapper *walloc(struct wrapper *root)
{
if (root == NULL){
root = (struct wrapper *) malloc(sizeof(struct wrapper));
root->data = strdup("H");
}
return root;
}
int main(){
struct wrapper *root;
root = NULL;
root = walloc(root);
//free(root->data);
return 0;
}
這裏是Valgrind的輸出:
$ valgrind --leak-check=full ./leak
==26489== Memcheck, a memory error detector
==26489== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==26489== Using Valgrind-3.10.0 and LibVEX; rerun with -h for copyright info
==26489== Command: ./leak
==26489==
==26489==
==26489== HEAP SUMMARY:
==26489== in use at exit: 2 bytes in 1 blocks
==26489== total heap usage: 2 allocs, 1 frees, 1,790 bytes allocated
==26489==
==26489== 2 bytes in 1 blocks are definitely lost in loss record 1 of 1
==26489== at 0x4C29F90: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==26489== by 0x4EB79C9: strdup (in /usr/lib/libc-2.20.so)
==26489== by 0x400542: walloc (leak.c:13)
==26489== by 0x400542: main (leak.c:23)
==26489==
==26489== LEAK SUMMARY:
==26489== definitely lost: 2 bytes in 1 blocks
==26489== indirectly lost: 0 bytes in 0 blocks
==26489== possibly lost: 0 bytes in 0 blocks
==26489== still reachable: 0 bytes in 0 blocks
==26489== suppressed: 0 bytes in 0 blocks
==26489==
==26489== For counts of detected and suppressed errors, rerun with: -v
==26489== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
「它是很好的做法,即使該程序在主函數結束時終止手動自由的一切嗎?」是的,即使操作系統釋放內存,也要這樣做。 'free()'可以暴露程序中的錯誤,否則很難找到它們。在完成分配代碼後直接執行解除分配是一種好習慣。 – Lundin 2014-09-23 06:35:24
我沒看到這個。我看到8個字節肯定丟失('root'),2個字節間接丟失('root-> data')。你能發佈valgrind的完整輸出嗎? – 2014-09-23 06:38:07
你應該'#include',因爲編譯器可以用'strdup'(和[GCC](http://gcc.gnu.org/)有時候做)「神奇」的東西 –
2014-09-23 06:42:15