Read access violation in dynamic stack implementation

#include <iostream>
#include <conio.h>

using namespace std;

struct Node
{
int info;
Node *next;
};

Node *top = nullptr;
Node *np = nullptr;
Node *temp = nullptr;

void Display()
{
temp = top;
cout << "The stack at its current state is: ";
while (temp != NULL)
{
cout << temp->info << " ";
temp = temp->next;
}
cout << endl;
_getch();
}


void Push()
{
np = new Node;
cout << "Enter info: ";
cin >> np->info;
if (top == NULL)
top = np;
else
{
np->next = top;
top = np;
}
Display();
}

void Pop()
{
if (top == NULL)
cout << "Underflow" << endl;
else
{
cout << "The element being deleted is: " << top->info;
top = top->next;
}
Display();
}

void main()
{
int choice = 1;
while (choice != 0)
{
cout << "1. Push" << endl;
cout << "2. Pop" << endl;
cout << "3. Display" << endl;
cout << "0. Exit" << endl;
cin >> choice;
switch (choice)
{
case 1:
{
Push();
break;
}
case 2:
{
Pop();
break;
}
case 3:
{
Display();
break;
}
case 0:
exit(0);
default:
break;
}
}
}

When the Display() function is called during runtime,

Unhandled exception thrown: read access violation.
**temp** was 0xCDCDCDCD. occurred

What does this error mean? How do I fix it? Also, I am sorry but the indentation does not show up here.
Last edited on
Push() is wrong.
Why?
1
2
np->next = top;
top = np;


top->next is never NULL, so you don't know the last node.

and top should never point back to the node pointing to it in a linked list.
Registered users can post here. Sign in or register to post.