2016-11-13 162 views
0

我正在運行valgrind,它告訴我,我需要釋放一些東西,我不知道我會在那裏做。它明確指出了這一行 「toInsert->值= linkedlist->副本(元素);內存泄漏C免費()

會在哪裏我自由奔跑和什麼樣的數據

?」 從Valgrind的

void linkedlist_append(LinkedList *linkedlist, void *element) { 

ListNode *toInsert = (ListNode*)malloc(sizeof(ListNode)); 
toInsert->value = linkedlist->copy(element); 
toInsert->next = NULL; 
ListNode *last = linkedlist->head; 

if (last==NULL) 
    linkedlist->head = toInsert; 

else{ 
    while(last-> next !=NULL){ 
     last = last->next; 

    } 
    last->next = toInsert; 

} 
linkedlist->size++; 

} 

輸出:

> ^C==30515== 
==30515== HEAP SUMMARY: 
==30515==  in use at exit: 287 bytes in 47 blocks 
==30515== total heap usage: 95 allocs, 1,038 frees, 2,159 bytes allocated 
==30515== 
==30515== 247 bytes in 46 blocks are definitely lost in loss record 2 of 2 
==30515== at 0x4C28C20: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) 
==30515== by 0x4011AC: string_copy (string_fns.c:27) 
==30515== by 0x4012CE: linkedlist_append (linkedlist.c:87) 
==30515== by 0x4017BD: add_file (tester.c:194) 
==30515== by 0x400FE1: main (tester.c:136) 
==30515== 
==30515== LEAK SUMMARY: 
==30515== definitely lost: 247 bytes in 46 blocks 
==30515== indirectly lost: 0 bytes in 0 blocks 
==30515==  possibly lost: 0 bytes in 0 blocks 
==30515== still reachable: 40 bytes in 1 blocks 
==30515==   suppressed: 0 bytes in 0 blocks 
==30515== Reachable blocks (those to which a pointer was found) are not shown. 
==30515== To see them, rerun with: --leak-check=full --show-leak-kinds=all 
==30515== 
==30515== For counts of detected and suppressed errors, rerun with: -v 
==30515== ERROR SUMMARY: 2200 errors from 10 contexts (suppressed: 0 from 0) 
+0

通常,valgrind告訴你它發現問題的變量。你能告訴我們valgrind的輸出嗎? – Evert

+2

[請參閱此討論,爲什麼不在'C'中投射'malloc()'和家族的返回值。](http://stackoverflow.com/q/605845/2173917)。 –

+0

考慮到你'malloc'ed'toInsert',這可能是你想要釋放的變量。 – Evert

回答

3

Valgrind指出你永遠不會釋放malloc的位置。在終止程序之前,您需要遍歷列表中的所有元素。