Mike
Mike

Reputation: 477

How to correctly destruct linked-list?

For a class assignment I need to implement a destructor for the objects of linked-list I've created. I made a function called MakeEmpty that I called inside the destructor. It compiled correctly the first time, but now I am getting instant crashes with an error saying:

Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

Can someone help me figure out what is wrong? I ran the debugger and pointed out where it says the error is in the code.

WORD::~WORD()
{
cout << "Destructor Called"<<endl;

(*this).MakeEmpty();
}

And this is the MakeEmpty() function

void WORD::MakeEmpty()
{
alpha_numeric *p = (*this).front;

if((*this).IsEmpty())
{
    cout <<"Already empty"<< endl;
    return;
}

while(front != 0)
{
    front = front -> next;
    delete p;//<<<<---DEBUGGER SAYS ERROR HERE
    p = front;
}
return;
}

Upvotes: 0

Views: 1186

Answers (2)

Richard K.
Richard K.

Reputation: 171

You have a coding error... you need to: Bench check your code!

Write down the expected values of all variables at each statement and through each iteration of the loop. Don't skip any steps. This will make your coding error obvious.

After 30 years I do this in my head.. but I always do it to make sure what I've written is correct. This one habit will serve you well in years to come.

Upvotes: 0

Victor Hurdugaci
Victor Hurdugaci

Reputation: 28425

Since it's a homework I'm not going to give the solution but rather a hint.

while(front != 0)
{
    front = front -> next;
    delete p;//<<<<---DEBUGGER SAYS ERROR HERE
    p = front;
}

In this while, where in the list you start/end the deletion? And why?

Upvotes: 3

Related Questions