Reputation: 129
I know there's a lot of similar questions out there, but I haven't found anything that helps yet. I've been at this for several hours now and it's driving me crazy. I get a segmentation fault when a destructor is called for a variable that was created by the copy constructor.
//Copy Constructor
Stack::Stack(const Stack &aStack)
{
size = 0; //this is incremented as new items are pushed onto the stack.
cap= aStack.cap;
items = new int[aStack.cap]();
for (int i = 0; i < aStack.size; i++)
this->push(aStack.items[i]); //Adds an item if not full and increments size
// I have also tried: items[i] = aStack.items[i]
}
//Destructor
Stack::~Stack()
{
cap= 0;
size= 0;
delete [] items;
items = NULL;
}
I get the feeling I'm doing the copy constructor wrong, but I can't figure out what it is.
Upvotes: 3
Views: 16403
Reputation: 129
Well, I found it. I'll put it here for anyone as silly as I am (lacking basic c++ knowledge) so they don't spend hours looking for the same thing I was.
My problem was the destructor seemed to be working "selectively." It worked in some tests, but failed in others. After comparing the tests for hours, I finally found it.
The tests that were failing finished by testing the pop function, continuing until the stack was empty.
In my destructor, there is a line which says
delete [] items;
This would have been fine except my pop function had a line which read items[size-1] = NULL;
So in a way, every time pop removed an item, it was being NULLED/deleted before the destructor was called. Due to my very basic knowledge of c++, I was not aware that the delete command could not handle empty arrays. So, I simply got rid of the line that deleted the item ahead of time (essentially, to the end user, the item no longer exists because of encapsulation. The top index still changes so it's no longer accessible)
Anyway, final lesson: delete [] items
; does not handle empty arrays (which makes sense I guess. The delete command is expecting an array much longer than my final array was turning out to be).
Upvotes: 3
Reputation: 564
The line:
for (int i = 0; i < aStack.top; i++)
should be:
for (int i = 0; i < aStack.size; i++)
It's seg faulting because you are likely trying to access an out of range index or something similiar (undefined behaviour territory).
Upvotes: 1