An assertion faliure is killing me
I keep getting _BLOCK_TYPE_IS_VALID(phead->nBlockUse) during runtime. I have spent 3 hours messing around with it and found that it is somehow caused by the destructor? What i have figured out was that when my stack is empty, there wasnt a problem. but when there was something, it gave me this error. I checked online and my destructor and i dont know what is going on. Here are my all of my codes.
EDIT: i fixed the error but there s runtime error now...?
.cpp I have tried
开发者_StackOverflow社区stack::~stack() ////PROBLEM STILL HERE??
{
while (this)
{
top=top->next;
int x,y;
pop(x,y);
}
}
stack::~stack()
{
StackNode *nodePtr, *nextNode;
nodePtr = top;
while (nodePtr)
{
nextNode = nodePtr->next;
delete nodePtr;
nodePtr = nextNode;
}
}
stack::~stack() {
while (!isEmpty())
{ int x,y; pop(x,y); }
}
Yes. The problem is in the destructor. You are deleting the nodes there but you are not updating the top
pointer. As a result your isEmpty()
will malfunction as it checks the value of top
.
How to fix?
You've already taken care of deleting a node in the pop
function why duplicate the logic in the destructor? Keep calling pop
from the destructor till the stack is not empty.
The problem is in the destructor as you are not updating the top. Instead of again writing the code for deleting the elements you can simply call pop
function in the while
loop.
Look closely at the interaction between your destructor and IsEmpty(). IsEmpty() checks top
for nullness, but your destructor never updates top after deleting the head node.
I'd probably write the destructor like this:
stack::~stack()
{
StackNode *nodePtr, *nextNode;
nodePtr = top;
while (nodePtr)
{
nextNode = nodePtr->next;
delete nodePtr;
nodePtr = nextNode;
}
}
stack::~stack() //PROBLEM HERE??
{
StackNode *nodePtr, *nextNode;
nodePtr = top;
while (!isEmpty())
{
nextNode = nodePtr->next;
delete nodePtr;
nodePtr = nextNode;
}
}
bool stack::isEmpty()
{
if (!top)
return true;
else
return false;
}
Those two seem somehow wrong. Imagine your stack
is not empty. This means top
points to somewhere (therefor not null
). In order for your destructor to stop from accessing memory it should not, you use isEmpty()
which checks for null
in top. But in this piece of code, top
is never set to null
. Sooner or later you start delete
-ing memory you do not own.
精彩评论