I'm trying to learn C, and as many people, I've been a little stuck with pointers. Anyways, I made a recursive function that destroys my linkedlist, but as I've debugged, when I'm back from the function the head of the list is not null as it should be, so I'm guessing it's some basic misunderstanding with pointers. Here's the function:
void destroy(struct node* n){
if(!n) return;
destroy(n->next);
free(n);
n = NULL; }
Thanks in advance.
void deleteList(struct node** head_ref)
{
struct node* current = *head_ref;
struct node* next;
while (current != NULL) {
next = current->next;
free(current);
current = next;
}
*head_ref = NULL;
}
Try like this ....you can change names as you want. If you still need help let me know.
Head has been freed when this functions ends but it's not null. Everything in C is passed by value. So you pass a copy of the location of head into destroy. That memory is deallocated but head is not changed.
You could write this as:
destroy(&head);
void destroy(struct node** n){
if(!*n) return;
destroy(&((*n)->next));
free(*n);
*n = NULL;
}
You have to use a pointer pointing to your list, calling with destroy(&n):
/* clear complete list */
void destroy(struct node **n)
{
if (*n== NULL)
return;
if ((*n)->next == NULL)
{
free(*n);
*n= NULL;
}
else
{
struct node *iter = *n;
struct node *prev = NULL;
/* get last item and previous one */
while (iter->next != NULL)
{
prev = iter;
iter = iter->next;
}
prev->next = NULL;
free(iter);
/* repeat call */
clear(n);
}
}
Hope this may help you.
As I see the solution of spt025, my one seems to have a bit too much code. I am just a beginner as well ;)
来源:https://stackoverflow.com/questions/18412620/c-linked-list-destroy-function