简体   繁体   中英

Pop function linked list, glibc detected double free or corruption

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;
}
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 pop ed 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM