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

标签 c linked-list runtime-error glibc

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

* 检测到 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/

相关文章:

c - 如何实现【复制数组到链表】功能?

c# - 异常 : system. IO.FileNotFoundException : cannot find assembly or file Mysql. 数据

c - 我在哪里声明 x 和 y 以使这个 c 代码工作?

python - 如何根据指针地址获取指针内容

c - 检查指针是否到达字符串末尾时出错

c - 使用查找表进行优化

c - 尝试添加到链表时使用 Valgrind 无限循环 "Signal 11 being dropped"

c - 边的链接列表

c++ - Qt 5.1 应用程序无法在 QtCreator 之外的 Windows 8 上运行,运行时错误

javascript - SharePoint 2013,无法设置属性 'control' .load()