2
votes

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
Where do you get the error? What do you get from the debugger? What have you tried to find out yourself?too honest for this site
1) There is a need to update the caller side top. 2) free(new_node); new_node = new_node->next; : Do not use after release.BLUEPIXY

1 Answers

1
votes
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).