Reputation: 13
I am working on a program that uses doubly linked lists yet my destructor causes an error. I am not sure why this is occurring so an explanation would be great as well as possible steps for a solution.
~GroceryList()
{
ItemType *before=head, *current=head, *after=head;
for(int i=0; i<itemCount; i++)
{
before=current;
current=current->next;
after=current->next;
before->next=after;
after->prev=before;
delete current;
}
current=before=after=NULL;
};
Upvotes: 2
Views: 1781
Reputation: 206567
You have a logic error.
for(int i=0; i<itemCount; i++)
{
before=current;
current=current->next;
after=current->next;
before->next=after;
after->prev=before;
// Add some statements to print the conents of
// before, current, and after here to debug
// the memory problem.
delete current;
current = after; // Add this line.
}
Upvotes: 0
Reputation: 904
First of all you should show error msg.
I think below line is creating problem.
for(int i=0; i<itemCount; i++)
{
before=current; // this one
current=current->next;
after=current->next;
before->next=after;
after->prev=before;
delete current; // here you are deleting and again using `current` in first statement in loop?
}
Upvotes: 1