链接列表 C 代码挂起,没有从“释放”返回功能
对于我正在开发的程序,我有一个双向链表。我现在必须找出特定数据(称为 id )变为负数的特定节点,然后取消引用以下节点并释放内存。当我调用此函数(粘贴在下面)时,将执行最后一个打印语句并在屏幕上打印。但是程序不会返回到主程序。它只是挂起。 (在这个函数调用之后,我有另一个打印语句没有被执行,并且程序无限地挂在那里)。
static void clear_ghosts(particles *plist)
{
particles * temp = plist;
while(temp!=NULL) {
if(temp->p->id < 0)
{
break;
}
temp = temp->next;
}
if(temp)
{
particles * current = temp;
particles * next;
while(current !=NULL)
{
next = current->next;
free(current);
current = next;
}
temp = NULL;
}
printf("\n Finished Clearing \n");
return;
}
这里的plist
是一个structarticle*
类型的链表。 plist
具有数据 p
,它本身是一个结构体,并且具有诸如 id
等成员数据。我需要循环遍历列表并在以下情况下终止列表遇到负数的会员id。我得到输出“Finished Clearing”,但该函数没有返回到 main。
可能出了什么问题?
For a program that I am working on, I have a doubly linked list. I now have to figure out a particular node where a particular data (called id
) becomes negative, and then dereference the following nodes and also free the memory. When I call this function (pasted below), the last print statement is executed and prints on screen. However the program doesn't return to main. It simply hangs. (Right after this function call, I have another print statement which doesn't get executed and the program hangs there endlessly).
static void clear_ghosts(particles *plist)
{
particles * temp = plist;
while(temp!=NULL) {
if(temp->p->id < 0)
{
break;
}
temp = temp->next;
}
if(temp)
{
particles * current = temp;
particles * next;
while(current !=NULL)
{
next = current->next;
free(current);
current = next;
}
temp = NULL;
}
printf("\n Finished Clearing \n");
return;
}
Here plist
is a linked list of type struct particle *
. plist
has data p
which itself is a struct and has member data like id
etc. I need to loop through the list and terminate the list when the member id that is negative is encountered. I am getting the output "Finished Clearing", but the function is not returning to main.
What could be going wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您确定您尝试
free()
的所有元素都已使用malloc()
分配吗?例如,如果其中一些指针指向堆栈上的内存,那么当您尝试free()
它们时,可能会发生各种可怕的事情。Are you sure all elements you are trying to
free()
have been allocated withmalloc()
? If, for example, some of those pointers point to memory on the stack, all kinds of horrible things might happen when you try tofree()
them.既然你说它是一个双链表,你应该将前一个元素的下一个指针设置为 NULL:
Since you say its a double-linked list you should set the previous element's next pointer to NULL: