【问题标题】:Segmentation fault (core dumped) STACK分段错误(核心转储)堆栈
【发布时间】:2015-05-06 14:39:58
【问题描述】:

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

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,但我不知道为什么?

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

【问题讨论】:

  • z->next = z; 这有什么意义?分配 2 个头节点而不是 1 个有什么意义?如果使用现代编译器编译,您的代码也不是有效的 C。所有函数都必须有一个返回类型,隐式 int 已在 16 年前从语言中移除。

标签: c stack


【解决方案1】:

正在推送中:

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

现在你的流行音乐也有一些问题:

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

这应该是:

t = head;
head = head->next;

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

我真的建议在编写代码之前将其画在纸上。它将帮助您更快地学习。

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

z->next = z;

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

【讨论】:

  • 另外,你有一个 stackinit 函数,但我不相信你曾经调用过它。这意味着head 无效。
  • 唷,我也会提到那个。我全神贯注于解释列表逻辑。
  • 哦,是的,我不明白你的所有解释,但它有效。或者,我的解决方案也可以工作,只要我在我的 main 函数的开头添加 stackinit() !非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
  • 2021-06-03
相关资源
最近更新 更多