I’m trying to implement a simple stack using linked lists. When I run the code below, I get
6
<some random integer>
I’ve been looking for my mistake for hours now without success. I guess there is an uninitalized Variable somewhere, but I can’t seem to find it.
#include <iostream>
using namespace std;
class node {
public:
node operator = (const node&);
node(int d,node* n): data(d), prev(n) {}
node(){}
node* prev;
int data;
};
node node::operator = (const node &n) {
node r(n.data, n.prev);
return r;
}
class stack {
public:
stack();
void push(int);
int pop();
bool empty();
private:
node* top;
};
stack::stack() {
top = 0;
}
bool stack::empty() {
return top == 0;
}
void stack::push(int x) {
node n(x,top);
top = &n;
}
int stack::pop() {
if (!empty()) {
node r = *top;
//cout << "r.data: " << r.data << endl;
top = top->prev;
return r.data;
}
else {
cout << "Stack empty!" << endl;
return 0;
}
}
int main() {
stack a;
a.push(5);
a.push(6);
cout << a.pop() << endl;
cout << a.pop() << endl;
}
Now the thing that totally confuses me, is that when I uncomment the line
//cout << "r.data: " << r.data << endl;
for testing purposes, the output changes to
r.data: 6
6
r.data: 6
6
Why would that happen?
This code is wrong:
Here you create a local variable, and then set
topto point to that. But when the function returns then the local variable does not exists any more, andtoppoints to some memory that is not valid.You need to create a new
nodeon the heap with thenewoperator:Of course, now you have to make sure the allocated nodes are free’d when your done. This should be done in a destructor in
stackthat pops all nodes, and inpopyou need to use thedeleteoperator to free the memory.