C free()中的内存泄漏

  • 本文关键字:内存 泄漏 free
  • 更新时间 :
  • 英文 :


我正在运行valgrind,它告诉我,我需要释放一些东西,我不确定我会在哪里这样做。它特别指向这一行"toInsert->value = linkedlist->copy(element);

我将在哪里运行,在什么数据上运行?

"

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++;
}

Valgrind输出:

> ^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)

Valgrind指向一个永远不会被释放的malloc的位置。在终止程序之前,需要遍历列表并释放其中的所有元素。