0
#include <stdio.h>
#include <stdlib.h>

typedef struct x {
    int data;
    struct x *next;
} stack;

int main(){
    stack *head;
    int choice, num;
    head = NULL;

    /* function prototypes */
    void push(stack **head, int item);
    int pop(stack **head);
    int peek(stack *head);

    /* program */
    do{
        printf("\n1. Push Element\n2. Pop Element\n3. Peek The First Element\n4. Exit");
        printf("\nEnter your choice: ");
        scanf("%d", &choice);
        switch(choice){
            case 1:
                printf("\n\nEnter the number to be pushed: ");
                scanf("%d", &num);
                push(&head, num);
                break;
            case 2:
                printf("%d\n", pop(&head));
                break;
            case 3:
                printf("%d is the top element\n", peek(head));
                break;
            default:
                system("cls");
                break;
        }
    }while(choice!=4);
}

void push(stack **head, int item){
    stack *ptr;
    ptr = (stack *)malloc(sizeof(stack));
    ptr->data = item;
    ptr->next = *head;
    *head = ptr;
    free(ptr);
}

int pop(stack **head){
    if(*head == NULL) return -1;
    int item = (*head)->data;
    *head = (*head)->next;
    return item;
}

int peek(stack *head){
    if(head == NULL) return -1;
    return head->data;
}

What is the problem in the code? Whenever I pop or peek a memory address is being printed instead of the value pushed. When peek is called a memory address is shown which is popped when pop function is called and after that whenever calling the pop function it shows different memory address no matter how many times i call the function. Can't find out the problem in the code. Please help.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • 1
    Other than `free` being wrong in `push` (as already mentioned in an answer), [don't cast the result of malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – Enzo Ferber Sep 29 '15 at 15:49

1 Answers1

4

You're freeing the pointer you want to display. In push, when you free(ptr), head is pointing to ptr. So, essentially you're freeing head. This means that nothing ever gets pushed on to the stack. What you should do is free the data on pop instead, and also implement a function to go through the stack and free everything still remaining in the stack on exit.

Tejas Sharma
  • 462
  • 1
  • 4
  • 17