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