Reputation: 11
I'm new to programming and I'm having issues with deleting a linked list recursively.
int main(void)
{
node *head = NULL;
head = push_f(head);
head = push_f(head);
head = push_f(head);
print(head);
delete_l(head);
print(head);
}
void delete_l(node *head)
{
if (head == NULL)
{
return;
}
delete_l(head->next);
free(head);
}
It however only seems to delete the last 2 nodes. enter image description here
Upvotes: 1
Views: 88
Reputation: 310960
After calling the function delete_l
delete_l(head);
the pointer head
in main
was not changed because the function deals with a copy of the value of the pointer. So it still points to the deleted first node of the list.
The function indeed freed the allocated memory. And the next call of the function print
print(head);
just invokes undefined behavior by accessing the freed memory.
Upvotes: 1