简体   繁体   English

释放双向链接列表-挂起

[英]Free-ing a doubly linked list - hangs

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. 没什么要注意的:plist是一个双向链接列表,带有prevnext和指向结构的指针,该结构又将int和double作为数据,并将链表本身作为成员数据。 Do you think that since plist has pointers to other data, it hangs? 您是否认为plist具有指向其他数据的指针,所以它挂起了? 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. 在那种情况下,我什至要释放指针,并在clean_list上运行plist成员相同的clean_list I tried searching around for a solution and I didn't find any. 我尝试搜索解决方案,但没有找到任何解决方案。 Please help. 请帮忙。

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. 假设plist是一个包含三个元素的循环链接列表:A <-> B <-> C <-> A,并且plist指向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. 当您的代码运行时,它将:释放A,前进到B,释放B,前进到C,释放C,然后前进到是A的已释放内存。现在您的代码崩溃了。 (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;

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). 请尝试在gdb中执行您的程序,使其崩溃并查看回溯跟踪(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. 跟踪完成后,请与一些代码一起发布。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM