1
votes

I am trying to free a doubly linked list. This is the function I am using.

static void clean_list(particles * plist)
{

  particles  *n_list = plist;
  particles *temp_nlist;

  while(n_list){
    temp_nlist = n_list->next;

    free(n_list);
    n_list = temp_nlist;

  }
 }

When I try to call this function in my program, the program hangs without returning from this function. Few things to note: plist is a doubly linked list with a prev, a next, a pointer to a struct which in turn has int and double as data and a linked list itself as member data. Do you think that since plist has pointers to other data, it hangs? In that case I have even tying freeing the pointer, and running the same clean_list on the linked list which a member of plist. I tried searching around for a solution and I didn't find any. Please help.

2
This is probably caused by the creation of the list (most likely next never becomes NULL).cnicutar
There is no inherent reason that should cause a problem. There is probably a problem with the list itself. Maybe it is circular. You should print out some information about the nodes you are freeing to get a better understanding of what is going on.Vaughn Cato
If you want any help solving this you will have to show the code that creates the list.David Heffernan
I removed my answer since it was invalid.rzetterberg

2 Answers

1
votes

I agree with the other commenters that this question needs more information about the initial conditions of your problem before it can be properly answered. However, a scenario that causes your code to fail comes to mind immediately.

Suppose that plist is a circularly linked list with three elements: A <-> B <-> C <-> A, and plist points to A.

When your code runs, it will: deallocate A, advance to B, deallocate B, advance to C, deallocate C and then advance to the freed memory that was A. Now your code blows up. (or runs forever)

Since it is a doubly linked list, you should use your previous links to null out your next links before deallocating. And for good measure, null out your prev links as well.

temp_nlist = n_list->next;
temp_nlist->prev = NULL;
if (n_list->prev != NULL) n_list->prev->next = NULL;

free(n_list);
n_list = temp_nlist;
0
votes

It is probably not a problem with the function itself but with its leftovers, the head, tail or prev pointers that were not cleaned.

Please try to execute your program within gdb, let it crash and the look at the back trace (bt). I am sure it will give you a better understanding of whats going on. After you have the trace, please post it with some of your code.