the problem is printf() in pop() method display the weird address and don't run anymore. the print result is below.
push (10)
push (20)
push (30)
push (40)
40
-842150451
Here's the entire code.
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}node;
node* head = NULL;
void init(){
head = (node*)malloc(sizeof(node));
head->data = 0;
head->next = NULL;
}
void push(int data){
node* temp = (node*)malloc(sizeof(node));
if(temp == NULL){
printf("Out Of Memory");
}else{
head = (node*)malloc(sizeof(node));
temp->data = data;
temp->next = head;
head = temp;
printf("push (%d)\n", data);
}
}
void pop(){
node* temp;
if(head == NULL) return;
temp = head;
printf("%d\n", head->data);
head = head->next;
free(temp);
}
void main(){
push(10);
push(20);
push(30);
push(40);
pop();
pop();
pop();
pop();
}
and this pop method doesn't work. It display 40 at first time.
and then print -842150451. I don't get it why I receive this weird number.
void pop(){
node* temp;
if(head == NULL) return;
temp = head;
printf("%d\n", head->data);
head = head->next;
free(temp);
}