Reputation: 193
does anyone know whats wrong with this ?? it keeps giving me an "Assertion Failed" _BLOCK_TYPE_IS_VAILD(pHead->nBlockUse) when it tries to use the detructor on a non empty stack EDIT:MORE CODES:
class stack
{
private:
struct StackNode
{
int x;
int y;
StackNode *next;
};
StackNode *top;
public:
stack()
{ top = NULL; }
~stack();
stack::~stack()
{
StackNode *nodePtr,*nextNode;
nodePtr=top;
while (nodePtr!=NULL)
{
nextNode=nodePtr->next;
delete nodePtr;
nodePtr=nextNode;
}
}
main.cpp
mouse_position.push(mouse_x,mouse_y);
print_stack(mouse_position);
void print_stack(stack m)
{
int tempx=0;
int tempy=0;
// while(!m.isEmpty()){
// m.pop(tempx,tempy);
cout<<tempx<<tempy<<endl;
// }
}
Upvotes: 1
Views: 1378
Reputation: 8644
From the code you posted, it seems the problem is the missing copy constructor. Consider the following code:
stack mouse_position;
// fill mouse_position
print_stack(mouse_position);
When you call print_stack
, you make a bitwise copy of mouse_position
. When print_stack
exits, that copy (namely m
) is destroyed, calling delete on its top
member, which is exactly the same top
of mouse_position
. When mouse_position
is deleted, you're deleting its top
twice.
Then again, there could be more bugs lurking in the code you haven't posted yet.
Upvotes: 4
Reputation: 96241
You copy your stack when passed into print_stack
and didn't follow the rule of three What is The Rule of Three? which results in a double deletion and your problem.
Unless you're doing this as an exercise, use std::stack
instead - it's been tested and debugged for years.
Upvotes: 2
Reputation: 57688
Some things to look at:
stack
destructor.class
stack
.std::stack
and
std::list
.Edit your post to show more context for more detailed help.
Upvotes: 2