【问题标题】:Pop function linked list, glibc detected double free or corruption弹出函数链表,glibc 检测到双重释放或损坏
【发布时间】:2016-04-21 22:21:40
【问题描述】:

我在尝试运行此程序时收到此错误:

* 检测到 glibc * ./a.out: double free or corruption (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;
}

【问题讨论】:

  • 你从哪里得到错误?你从调试器中得到什么?你试图找出自己的什么?
  • 1) 需要更新调用方top。 2)free(new_node); new_node = new_node-&gt;next;:发布后请勿使用。

标签: c linked-list runtime-error glibc


【解决方案1】:
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_nodetop 的值相同。
  • 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 **top) 传递。这样你就可以直接使用结果(当然,假设堆栈不为空)。

【讨论】:

    猜你喜欢
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多