[英]Linked List C code hangs without returning from 'free-ing' function
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. 现在,我必须找出一个特定的节点,其中特定的数据(称为
id
)变为负数,然后取消引用以下节点并释放内存。 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
是类型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. plist
包含数据p
,它本身是一个结构,并具有id
等成员数据。我需要遍历该列表,并在遇到负ID的成员id时终止该列表。 I am getting the output "Finished Clearing", but the function is not returning to main. 我得到输出“ Finished Clearing”,但功能未返回到main。
What could be going wrong? 可能出什么问题了?
Are you sure all elements you are trying to free()
have been allocated with malloc()
? 您确定要
free()
所有元素都已使用malloc()
分配了吗? If, for example, some of those pointers point to memory on the stack, all kinds of horrible things might happen when you try to free()
them. 例如,如果其中一些指针指向堆栈上的内存,则当您尝试
free()
它们时,可能会发生各种可怕的事情。
Since you say its a double-linked list you should set the previous element's next pointer to NULL: 由于您说的是双向链接列表,因此您应该将上一个元素的下一个指针设置为NULL:
if (temp)
{
if ( temp != plist )
{
temp->prev->next = NULL;
}
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.