0

我使用双向链表在 C 中构建了一个堆栈结构,并且在弹出列表的最后一个元素时遇到了段错误。这是 pop 方法和一些相关的全局变量:

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

很明显,我不应该只是将头部和尾部设置为空。我应该怎么做?

4

1 回答 1

1

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.

于 2013-04-22T20:58:43.717 回答