分段错误(核心已转储)堆栈

Segmentation fault (core dumped) STACK

我正在尝试实现一个简单的堆栈,但我遇到了分段问题:

struct node {
    int key;
    struct node *next;
};
static struct node *head, *z, *t;

int main(int argc, char** argv) {
    push(5);
    push(9);
    push(8);
    push(pop()+pop());
    push(4);
    push(6);
    push(pop()*pop());
    push(pop()*pop());
    push(7);
    push(pop()+pop());
    push(pop()*pop());
    printf("%d\n", pop());
    return (EXIT_SUCCESS);
}

stackinit() {
    head = (struct node*) malloc(sizeof *head);
    z = (struct node*) malloc(sizeof *z);
    head->next = z;
    head->key = 0;
    z->key = 0;
    z->next = z;
}

stackempty() {
    return head->next == z;
}

int pop() {
    int x;
    t = head->next;
    head->next = t->next;
    x = t->key;
    free(t);
    return x;
}

push(int v) {
    t = (struct node*) malloc(sizeof *t);
    t->key = v;
    t->next = head->next;
    head->next = t;

}

给出的错误是:Segmentation fault (core dumped)

我知道我正在寻找一个不存在的 ID,但我不明白为什么?

有人知道为什么吗? 谢谢 最好的问候

推送中:

t->next = head->next
head->next = t;

应该是:

t->next = head;
head = t;

你要做的是先假装t是新的头,所以你设置下一个指针指向当前的头。如果我们想象 headA 而堆栈下面的元素是 B,我们首先将 t 搁浅在一边:

t = new_node;
-- t  A(head)->B->...->NULL

第一行像这样将 t 钩到头部:

t->next = head;
-- t->A(head)->B->...

然后第二个让t成为新的头。

head = t;
-- t(head)->A->B->...->NULL

现在你的 pop 也有一些问题:

t = head->next;
head->next = t->next;

这应该是:

t = head;
head = head->next;

我们所做的是将当前的头部复制到t这样我们就不会丢失它,然后下一行是弹出堆栈的实际行(将头部更改为指向到堆栈下方的元素)。

我强烈建议您在编写代码之前将其画在纸上。它会帮助你学得更快。

最后但同样重要的是,您需要调用此 stackinit 函数来正确初始化所有内容,但您没有调用它。在里面,我不确定 z 应该做什么,但这肯定是不正确的:

z->next = z;

这使得 z 循环,像这样:z->z->z->z->...