gpt4 book ai didi

c - pop函数链表,glibc检测到double free or corruption

转载 作者:太空宇宙 更新时间:2023-11-03 23:44:40 25 4
gpt4 key购买 nike

当我尝试运行这个程序时收到这个错误:

* 检测到 glibc * ./a.out:双重释放或损坏(fasttop):0x0000000001926070 ***

我试图在 C 中创建自己的 pop 函数,但出现了上述错误。我不确定哪里出错了。

struct node *pop(struct node *top, int *i)
{
struct node *new_node = top;
int count = 0;

if ( new_node == NULL) {
return top;
}

while ( new_node != NULL && (count < 1)) {
*i = new_node->value;
free(new_node);
new_node = new_node->next;
count++;
}

return new_node;
}

最佳答案

free(new_node);
new_node = new_node->next;

您在释放对象之后访问它。这会调用未定义的行为。一旦释放,您不得访问该对象。

改为使用临时指针:

struct node *next = new_node->next;
free(new_node);
new_node = next;

这才是你错的真正原因。


但是,您的代码太复杂了:

  • if (new_node == NULL) 是多余的,因为 while 循环已经测试了一个空指针new_node无论如何,top 的值相同。
  • count 将使您的循环最多交互一次。所以你根本不需要循环。

看这个:

struct node *pop(struct node *top, int *i)
{
if ( top != NULL) {
struct node *next = top->next;
*i = top->value;
free(top);
top = next;
}
return top;
}

请注意,返回 poped 值并传递一个指针作为top(struct node * *顶部)。这样您就可以直接使用结果(当然,假设堆栈不为空)。

关于c - pop函数链表,glibc检测到double free or corruption,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36781454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com