Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting a whole linked list

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;
}
like image 508
user90790 Avatar asked Oct 29 '25 07:10

user90790


1 Answers

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;
}
like image 120
P.P Avatar answered Oct 30 '25 22:10

P.P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!