user1874204
user1874204

Reputation: 1

Popping sole member of stack

I built a stack structure in C using a doubly-linked list and I'm running into a segfault when popping the last element of the list. Here's the pop method and some relevant globals:

typedef struct node {

    int value;
    struct node *prev;
    struct node *next;

} node;

node *head = NULL;
node *tail = NULL;
int stackSize = 0;

int removeFromStack(){
    node *tempNode = head;

    if(stackSize <= 0){
        emptyStackError();
    }

    int val = head->value;

    if(stackSize == 1){
        head = NULL; //Segfaults here
        tail = NULL;
    }

    else{
        head = head->next;
        head->prev = NULL;
    }

    free(tempNode);
    stackSize--;
    return val;
}

So clearly I'm not supposed to be just setting the head and tail to null. What should I be doing instead?

Upvotes: 0

Views: 59

Answers (1)

Thibaut
Thibaut

Reputation: 2420

The error is not likely to be where you said. You just assign a value to a pointer. My guess is that it is coming from two lines above.

Before:

int val = head->value;

Please add:

assert(head != NULL && "Oops, the counter is messed up");

And try to run your code again.

If the assert fires, track all usage of stackSize. If it does not, it doesn't necessarily mean that the pointer is not random, or points on de-allocated space. Comment everything but head->value in this function. Then try to create a list, push one element, then try call removeFromStack. Then try push two elements, pop one and try removeFromStack again.

My guess is your counter get corrupted somewhere in another function.

Upvotes: 1

Related Questions