Home > other >  Not displaying proper output when display() function is called in stack in C
Not displaying proper output when display() function is called in stack in C

Time:02-23

Below is the implementation of a stack data structure using linked list in C.

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

struct stack
{
    int data;
    struct stack *next;
};
struct stack *top = NULL;

void push(int d)
{
    struct stack *nptr;
    nptr = (struct stack *)malloc(sizeof(struct stack));
    if (top == NULL)
    {
        nptr->data = d;
        nptr->next = NULL;
        top = nptr;
    }
    else
    {
        nptr->data = d;
        nptr->next = top;
        top = nptr;
    }
}
void display()
{
    while (top != NULL)
    {
        printf("%d\n", top->data);
        top = top->next;
    }
}

void pop()
{
    struct stack *temp = top;
    top = top->next;
    free(temp);
}

int main()
{
    push(5);
    push(6);
    push(7);
    pop();     // This works fine
    display(); // This works as well
    pop();     // The element does not pop when called.
    display(); // The stack does not display.
    return 0;
}

The final output of the program is:

6
5

shell returned -1073741819

The actual output of the program should be:

6
5
5

I couldn't find anything wrong in the program but the output is not as expected. Please help me out. Thanks

CodePudding user response:

With the first call to display() you destroy your stack.
This is because you manipulate a global variable which should afterwards be unchanged.
Your pop() does not check for NULL and at the call after display() unconditionally dereferences the pointer which indeed is NULL because of the misbehaviour of display() and not protecting against unexpected NULL.

  • Related