Noder
Noder

Reputation: 323

pop() method of stack linked list using C has an error

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);
}

Upvotes: 0

Views: 68

Answers (1)

Stephen Docy
Stephen Docy

Reputation: 4788

You have a weird, extra malloc in push(), I got rid of it and things looked much better:

void push(int data) {

    node* temp = (node*)malloc(sizeof(node));
    if (temp == NULL) {
        printf("Out Of Memory");
    } else {
        //head = (node*)malloc(sizeof(node));     <---- this is your problem
        temp->data = data;
        temp->next = head;
        head = temp;
        printf("push (%d)\n", data);
    }
}


push (10)
push (20)
push (30)
push (40)
40
30
20
10

Upvotes: 2

Related Questions