I am implementing a linked stack of strings in C++, mainly for fun. Every object of the list is a Node
instantiation, and the list itself is an instance of StackOfStrings
. Right now I instantiate a new Node
using new
and everything works fine, but I can't seem to figure out how to instantiate a Node
on the stack and refer to it at a later point in the code.
I tried changing first = new Node;
with first = &Node();
inside the push()
method, but then I get a run-time std::bad_alloc
error when I call the pop()
method. My guess is that this Node
gets created on the stack and is destroyed as soon as the program exits the push()
method. So my question is: is there a way I can create assign to first
a Node
created on the stack and retain it for later use?
I am including the bare bones of the code, I added a comment next to the line that is causing me problems.
class StackOfStrings
{
public:
StackOfStrings() {}; // Could be omitted, default constructor
void push(std::string item)
{
Node* old_first = first;
first = new Node; // *** my question revolves around this line ***
// *** "first = &Node()" does not work ***
// *** how can I have a Node on the stack? ***
first->setItem(item);
first->setNext(old_first);
}
std::string pop()
{
std::string item = first->getItem();
first = first->getNext();
return item;
}
private:
Node *first = nullptr;
};
For completeness, this is the Node
class:
class Node
{
public:
std::string getItem() { return item; }
Node* getNext() { return next; }
void setItem(std::string item) { this->item = item; }
void setNext(Node *node) { this->next = node; }
private:
std::string item;
Node* next = nullptr;
};
edit: by mistake I wrote *Node instead of &Node. I updated the question.
edit 2: a little experiment I tried:
- I called the
push()
method ofStackOfStrings
to insert the word "hello" inside the linked list. - inserted a breakpoint inside the
setItem()
method ofNode
to check that the world "hello" was saved in memory. Indeed, at memory address0x00FFF900
I found the values68 65 6c 6c 6f
, which corresponds to "hello" in ASCII - I then placed another breakpoint inside the call to
getItem()
in order to analyze the same memory address again. What I found nowa0 fb ff 00 28
which is garbage and certainly not "hello".