Pop function linked list, glibc detected double free or corruption

时间:2016-04-21 22:21:40

标签: c linked-list runtime-error glibc

I am recieving this error when I attempt to run this program:

* glibc detected * ./a.out: double free or corruption (fasttop): 0x0000000001926070 ***

I attempted to create my own pop function in C and it is giving me the error above. I'm not sure where I went wrong.

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 个答案:

答案 0 :(得分:1)

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

You access the objct after you freed it. This invokes undefined behaviour. Once released, you must not acce the object.

Instead use a temporary pointer:

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

That is the actual cause for your fault.


However, your code is far too complicated:

  • The if ( new_node == NULL) is superfluous,as the while loop already tests for a null pointer and new_node is the same value as top anyway.
  • count will make your loop interate at most once. So you don't need a loop at all.

See this:

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;
}

Note it is likely better to return the poped value and pass a pointer to pointer as top (struct node **top). That way you can use the result directly (presuming the stack is not empty, of course).