0

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

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Oh, gosh! So thank you! When I noticed my problem by your answer. I felt being stupid. I think I didn't understand the logic well. but now clear. so thank you!
Don't sweat it...dynamic memory can be a tricky concept at first, but it looks like you are getting the hang of it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.