【发布时间】: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 年前从语言中移除。