释放双向链表 - 挂起
我正在尝试释放一个双向链表。这是我正在使用的功能。
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;
}
}
当我尝试在程序中调用此函数时,程序挂起而不会从该函数返回。需要注意的几点:plist 是一个双向链表,其中包含一个 prev
、一个 next
、一个指向结构体的指针,该结构体又包含 int 和 double 作为数据以及链表本身作为会员数据。您认为既然 plist 有指向其他数据的指针,它就会挂起吗?在这种情况下,我什至绑定释放指针,并在 plist 成员的链接列表上运行相同的 clean_list
。我尝试四处寻找解决方案,但没有找到任何解决方案。请帮忙。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我同意其他评论者的观点,即这个问题需要更多有关问题初始条件的信息,然后才能正确回答。然而,导致您的代码失败的场景立即浮现在脑海中。
假设plist是一个循环链表,包含三个元素:A <-> B<-> C<-> A,plist 指向 A。
当你的代码运行时,它将:释放 A,前进到 B,释放 B,前进到 C,释放 C,然后前进到 A 的释放内存。现在你的代码爆炸了。 (或永远运行)
由于它是一个双向链表,因此您应该在释放之前使用先前的链接来清空下一个链接。为了更好地衡量,也取消你以前的链接。
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.
这可能不是函数本身的问题,而是函数的剩余部分、头、尾或 prev 指针没有清理的问题。
请尝试在 gdb 中执行您的程序,让它崩溃并查看反向跟踪 (bt)。我相信它会让您更好地了解正在发生的事情。获得跟踪后,请将其与您的一些代码一起发布。
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.