Reputation: 23
So I have a stack that is made up of randomly generated strings and then a pointer to the next item in my .cpp code. I then go through and pop each item off the stack and print them out. I get a seg fault at the end though so I'm guessing I'm trying to pop an item one past the stack where I do not own the memory.
I believe my copy constructor is incorrect - maybe it doesn't set the last value to null in my stack but I can't figure out why it's not setting the value to NULL when I put the line
newPrev->next = NULL;
here's my code (class only)
#include <string>
using namespace std;
class Stack
{
protected:
struct Node
{
string item;
Node* next;
}; // struct Node
public:
// constructor of an empty stack
Stack ()
{
head = NULL;
}
// copy constructor
Stack( const Stack & rhs )
{
if (rhs.head == NULL) {// check whether original is empty
head = NULL;
}else{
head = new Node;
head->item = rhs.head->item;
Node* newPrev = head;
// Now, loop through the rest of the stack
for(Node* cur = rhs.head->next; cur != NULL; cur = cur->next)
{
newPrev->next = new Node;
newPrev = newPrev->next;
newPrev->item = cur->item;
} // end for
newPrev->next = NULL;
} // end else
}
// destructor
~Stack ()
{
delete head;
}
// assignment
const Stack & operator=( const Stack & rhs )
{
return *this;
}
// query whether the stack is empty
bool empty () const
{
return false;
}
// add an item to the top of the stack
// this method is complete and correct
void push (const string & new_item)
{
Node* new_node = new Node;
new_node->item = new_item;
new_node->next = head;
head = new_node;
}
// remove the item on the top of the stack
void pop ()
{
if (head!=NULL){
Node *n = head;
head = head->next;
delete n;
}
}
// return the item on the top of the stack, without modifying the stack
string & top () const
{
return head->item;
}
private:
Node* head;
};
Upvotes: 0
Views: 224
Reputation: 567
Your copy constructor is fine. You didn't implement your bool Stack::empty()
function. I changed it to this:
// query whether the stack is empty
bool empty () const
{
return head == NULL;
}
And this ran just fine:
int main()
{
Stack s;
s.push("a");
s.push("b");
Stack b(s);
while(!s.empty())
{
cout << s.top() << endl;
s.pop();
}
while(!b.empty())
{
cout << b.top() << endl;
b.pop();
}
return 0;
}
Upvotes: 1