free(temp) 释放我队列的后部。我如何释放它
free(temp) frees the rear of my queue. How do I free it
好的,我有打印队列的功能。我使用临时节点遍历链表。
当我尝试释放临时节点时,它也会释放我队列的尾部(队列中的最后一个节点)
struct QNode *temp = q->front;
printf("Queue: %d", temp->value);
while (temp->next != NULL)
{
temp = temp->next;
printf(" -> %d", temp->value);
}
printf("\n");
free(temp);
我有一个很长的算法,如果我不释放临时文件,我将拥有数十万个垃圾内存。而且我买不起
规则是每个malloc
一个free
,因为你没有为你的临时节点分配space(只是一个指向前面的指针),你不必调用free
,无视即可。
在我看来你误解了free(temp)
在做什么。
free(temp)
将 不 释放 temp
相反,它将释放 temp
点 到.
循环后,temp
指向列表中的最后一个节点,因此调用 free(temp)
将 释放最后一个节点 。您的链表将被破坏,因为最后一个节点之前的节点现在指向一个释放的对象。
第二个误解似乎是 temp
需要被释放。 没有。
temp
是一个具有自动存储持续时间的对象(又名局部变量)。函数returns.
时会自动销毁
喜欢:
void printList(...)
{
struct QNode *temp = q->front; // temp is just a local variable
printf("Queue: %d", temp->value);
while (temp->next != NULL)
{
temp = temp->next;
printf(" -> %d", temp->value);
}
printf("\n");
// free(temp); Don't call free on temp
// temp will be automatically destroyed once the function completes
}
好的,我有打印队列的功能。我使用临时节点遍历链表。 当我尝试释放临时节点时,它也会释放我队列的尾部(队列中的最后一个节点)
struct QNode *temp = q->front;
printf("Queue: %d", temp->value);
while (temp->next != NULL)
{
temp = temp->next;
printf(" -> %d", temp->value);
}
printf("\n");
free(temp);
我有一个很长的算法,如果我不释放临时文件,我将拥有数十万个垃圾内存。而且我买不起
规则是每个malloc
一个free
,因为你没有为你的临时节点分配space(只是一个指向前面的指针),你不必调用free
,无视即可。
在我看来你误解了free(temp)
在做什么。
free(temp)
将 不 释放 temp
相反,它将释放 temp
点 到.
循环后,temp
指向列表中的最后一个节点,因此调用 free(temp)
将 释放最后一个节点 。您的链表将被破坏,因为最后一个节点之前的节点现在指向一个释放的对象。
第二个误解似乎是 temp
需要被释放。 没有。
temp
是一个具有自动存储持续时间的对象(又名局部变量)。函数returns.
喜欢:
void printList(...)
{
struct QNode *temp = q->front; // temp is just a local variable
printf("Queue: %d", temp->value);
while (temp->next != NULL)
{
temp = temp->next;
printf(" -> %d", temp->value);
}
printf("\n");
// free(temp); Don't call free on temp
// temp will be automatically destroyed once the function completes
}