The following program successfully builds up a stack , but the 2 operations pop and stack top are giving exception and wrong result respectively. Here is the program :
// Working with stack using Array
/*
* @author Suhail Gupta
*
*/
#include <iostream>
using namespace std;
char choice;
int *ptrToArray; // this will be a pointer to the array alias stack that we'll make
int stackSize;
int currentStackSize = 0;
int *firstElement = NULL; // this pointer stores the address of the first element in the stack. It initially points to NULL
void push();
void pop();
void stackTop();
int main() {
cout << "Enter the size of stack : ";
cin >> stackSize;
ptrToArray = new int[stackSize];
do {
push();
cout << "Push elements ? y/n ";
cin >> choice;
} while( choice == 'y');
cout << endl << "pop elements ? y/n ";
cin >> choice;
if( choice == 'y') {
pop();
}
cout << endl << "know the stack top ? y/n ";
cin >> choice;
if( choice == 'y') {
stackTop();
}
}
void push() {
if( currentStackSize == stackSize) { // check before pushing if the stack is full
cout << endl << "Stack-Overflow !";
} else {
int numberToPush;
cout << endl << "Enter the number to be pushed : ";
cin >> numberToPush;
firstElement = &numberToPush; // Store the address of the Last number inserted.This is the address of the first element in the stack
ptrToArray[currentStackSize] = numberToPush;
cout << "The element you just inserted : " << ptrToArray[currentStackSize] << endl;
currentStackSize++;
}
}
void pop() {
if( stackSize == 0 ) {
cout << "Stack Underflow !";
} else {
delete firstElement; // delete the memory allocated to the first element
firstElement = &ptrToArray[currentStackSize-1];
currentStackSize--;
}
}
void stackTop() {
if( firstElement == NULL) {
cout << endl << "Stack Underflow !" << endl;
} else {
cout << "The first element in the stack is : " << *firstElement;
}
}
The pushing operation works fine.But if i call the pop function the following message is displayed :

Second question :
Now just comment the statement where pop function gets called . The result that i get when trying to know the first element on the stack by calling the function stackTop() is The first element in the stack is : -858993460 . This is some garbage number that i didn’t enter while making up the stack. Why the statement *firstElement gives the wrong result then ?
numberToPushis a local variable and have a blocked scope toelsepart and you are taking the reference of it.This is resulting you the garbage.Edit: You need to understand that storage duration of global variables are different to that of local. Just taking the reference of local to a global variable doesn’t increase the life time of a local variable. As soon as it’s scope finishes, the variable ceases to exist.