I'm trying to implement a simple stack, but I have a segmentation problem:
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;
}
The error given is: Segmentation fault (core dumped)
I understand that I'm looking a id that not exist, but I don't find why?
Somebody knows why? Thanks Best regards