Reputation: 305
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;
}
Upvotes: 4
Views: 22972
Reputation: 5110
You are not changing the original head. You should pass the pointer to this head i.e. pointer to a pointer or should return changed head to the caller. Following is the code to return changed head to the caller. There are other answers showing pointer to pointer approach.
set_elem* destroy(set_elem *head) {
set_elem *current = head;
set_elem *next;
while (current != NULL) {
next = current->next;
free(current);
current = next;
}
head = NULL;
return head;
}
in caller,
head = destroy(head);
Upvotes: 1
Reputation: 3357
when you copy head pointer passed into the function, head node is unaffected. You have to pass reference to the pointer to the head,then you will be able to delete head pointer. This can be also done by passing a pointer to the pointer to the head of the linked list but I find passing a reference more convenient. Following are the changes to your code.
void destroy(set_elem*& head)
{
set_elem* current = head;
set_elem* next;
while (current != NULL)
{
next = current->next;
free(current);
current = next;
}
*head = NULL;
}
Upvotes: 1
Reputation: 47784
You're modifying only the local head
pointer
Use a double pointer to modify the head
, which would be later used for printing/processing
void destroy(set_elem** head)
{
set_elem* current = *head;
set_elem* next;
while (current != NULL)
{
next = current->next;
free(current);
current = next;
}
*head = NULL;
}
Upvotes: 0
Reputation: 121367
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;
}
Upvotes: 3