Home:ALL Converter>C memory leak, where there is no memory leak? (valgrind)

C memory leak, where there is no memory leak? (valgrind)

Ask Time:2022-06-16T20:59:28         Author:Toast

Json Formatter

valgrind is telling me that a specific line in my code creates a memory leak, but when looking at that line, it does not seem to even be able to create one.

I am working with this pretty simple Linked List struct list.h:

typedef struct _linekd_list{
    void* object;
    struct _linked_list* next;
}linked_list;

And this is how a list is initialized in list.c:

linked_list* newlist(){
    linked_list * list = malloc(sizeof(linked_list));
    list->next = NULL;  //As a flag, that there is no next element
    list->object = NULL;
    return list;
}

My queue works so, that the first object of the first linked_list is always NULL, the first object is stored in the next linked_list.

Now here is where the memory leak occurs:

int list_add(void* new_object, linked_list* list){
        while(list->next != NULL) {  //First go to the end of the queue
            list = list->next;
        }
        list->next = malloc(sizeof(linked_list)); //Vangrind says there is a leak
        list->next->next = NULL; //Set the next list-object to NULL (acts like a flag)
        list->next->object = new_object; //And now store the pointer of the actual object
        if(list->next->object == new_object) {
            return 0;
        } else {
            return 1;
        }
    return 0;
}

This is what valgrind tells me:

==33369== 16 bytes in 1 blocks are definitely lost in loss record 1 of 3
==33369==    at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==33369==    by 0x402219: list_add (list.c:11)
==33369==    by 0x4012D0: main (test_list.c:38)
==33369== 

Here is the function that recursively frees the list (no memory leak detected):

void free_list(linked_list* list){
    if(list->next != NULL) {
        free_list(list->next);
        free(list);
    }
}

Author:Toast,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/72646267/c-memory-leak-where-there-is-no-memory-leak-valgrind
yy