c - Pop function linked list, glibc detected double free or corruption -


i recieving error when attempt run program:

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

i attempted create own pop function in c , giving me error above. i'm not sure 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 objct after freed it. invokes undefined behaviour. once released, must not acce object.

instead use temporary pointer:

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

that actual cause fault.


however, code far complicated:

  • the if ( new_node == null) superfluous,as while loop tests null pointer , new_node same value top anyway.
  • count make loop interate @ once. don't need loop @ 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 better return poped value , pass pointer pointer top (struct node **top). way can use result directly (presuming stack not empty, of course).


Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -