#Clearing a linked list without memory leak

8 messages · Page 1 of 1 (latest)

gusty stag
#
/* linked_list.c */
void clear(linked_list* list) {
   while (list->head != NULL) {
      printf("freeing up: %i", list->head->data);
      node* tmp = list->head;
      list->head = list->head->next;
      free(tmp);
   }

   list->head = NULL;
   list->tail = NULL;
}
/* main.c */
int main(void) {
    linked_list list;
    initialize_linked_list(&list);
    node newnode, secondnode;
    initialize_node(&newnode, 4);
    initialize_node(&secondnode, 5);
    
    insert(&list, &newnode);
    insert(&list, &secondnode);
    print_list(&list);
    clear(&list);
    print_list(&list);

    return 0;
}

Outputs this:

sh-5.2$ ./test
5
4
free(): invalid pointer
Aborted (core dumped)

Why does it not free the nodes nor print anything?

brave zodiacBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

paper dune
gusty stag
#

my bad

#

$close

#

$solve

#

$solved

gusty stag
#

!solved