learner561
learner561

Reputation: 137

Memory Leak in C free()

I'm running valgrind and it's telling me that I need to free something and I'm not sure where I would do that. It specifically points to this line "toInsert->value = linkedlist->copy(element);

Where would I run free and on what data?

"

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

}

Output from 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)

Upvotes: 0

Views: 95

Answers (1)

doron
doron

Reputation: 28872

Valgrind is pointing you to the location of a malloc that is never freed. Before you terminate your program, you will need to iterate through the list an free all its elements.

Upvotes: 3

Related Questions