I am working with linked lists and i fill the structure but when I delete the whole structure and try to print the contents of the linked list (should be null), a list of numbers appear. I know it is probably a memory problem. Any suggestions of how to fix it?
Code for deleting whole linked list:
void destroy(set_elem *head)
{
set_elem *current = head;
set_elem *next;
while (current != NULL)
{
next = current->next;
free(current);
current = next;
}
head = NULL;
}
While your delete function works correctly, it doesn't set the head in the caller to NULL when you do head = NULL; as you are only modifying a local pointer, which causes to your later logic where you are trying to print the values by checking the value of head.
To modify the original pointer, pass a pointer to head and set *head=NULL;
void destroy(set_elem **head)
{
set_elem *current = *head;
/* rest is the same */
*head = NULL;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With