I just learnt about linked stacks and was coding one, by using a struct for nodes and a class 'menu' that houses all the functions like push, pop or display. I used a dynamically allocated 'tmp' node(not declared as a class variable) in those functions whenever needed. After I was done coding the function I 'delete'-d the 'tmp' and exited. But this is resulting in garbage values in my stack, though I am assured that the operations are otherwise working fine.
When I changed the dynamic alloc to static alloc of the 'tmp', my code worked fine, assuring that the other aspects of the code is correct. I even tried clearing the "delete tmp;" statements inside the push() and disp() and then also interestingly my code worked alright. I was instructed by my teachers at school that one should always 'delete' the mem allocated by 'new' operator to save mem leaks but I am confused so as to why the prevention itself is causing problems.
struct st //creating the stack nodes
{
int n;
st *nxt;
};
class menu //houses push(),pop(),disp()
{
st *top;
public:
menu()
{
top=NULL;
top->nxt=NULL;
}
void push(); //pushes new elements into stack
void pop(); //pops out elements from top of stack
void disp(); //displays the entire stack
~menu();
};
void menu::disp()
{
st *tmp=new st; //dynamically allocated node
if(top==NULL)
cout<<"Empty stack";
else
{
cout<<"The new stack is";
tmp=top;
while(tmp!=NULL)
{
cout<<tmp->n<<" -> ";
tmp=tmp->nxt;
}
}
delete tmp; // deleting the dynamic mem
}
void menu::push()
{
st *tmp= new st; //dynamically allocated node
cout<<"Enter the new element";
cin>>tmp->n;
tmp->nxt=NULL;
if(tmp==NULL)
cout<<"Overflow";
else if(top==NULL)
{
top=tmp;
}
else
{
tmp->nxt=top;
top=tmp;
}
delete tmp; // deleting the dynamic mem
}
void menu::pop()
{
cout<<"Deleting the top elememt"<<endl;
if(top==NULL)
cout<<"Underflow"<<endl;
else
{
cout<<"The deleted element is "<<top->n<<endl;
top=top->nxt;
}
}
menu::~menu()
{
st *tmp= new st;
while(top!=NULL)
{
tmp=top;
top=top->nxt;
delete tmp;
}
}
My logic is correct and it was proved when I used static mem alloc (or deleting the "delete tmp;") so acc to me it should work with dynamic mem alloc as well. But compiler keeps on feeding garbage values to my stack apart from the ones I entered.
I have an idea that I am allocating a mem space to 'tmp' at first but then I am bringing it into the already built stack and at the end I am deleting it when it becomes null. So in one sense I am not deleting the mem it was originally allocated. But if this is so then is it true that one can never use a dynamically alloc pointer as a temp variable? Because then one can never delete the mem without pre-storing the address in another static ptr. I feel this to be very crippling as I can't see any possible solution to the problem.
Any help on this matter and an easy to understand insight into dynamic pointers(alloc and dealloc) is welcome.