mem leak/crash
Apr 3, 2010 at 8:32pm UTC
can anyone spot where the problem is in the code below? when i compile it, half the time it runs properly, half the time it crashes. thankyou
main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
{
DLList<char > charTest;
charTest.pushFront('a' );
charTest.pushFront('b' );
charTest.pushFront('c' );
cout << charTest.popBack() << endl;
cout << charTest.popBack() << endl;
cout << charTest.popBack() << endl;
charTest.pushFront('a' );
charTest.pushFront('b' );
charTest.pushFront('c' );
cout << charTest.popFront() << endl;
cout << charTest.popFront() << endl;
cout << charTest.popFront() << endl;
}
DLList.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
T popBack ()
{
T popped;
if (head == NULL) //empty
{
popped = NULL;
}
else if (tail == head) //1 node
{
popped = tail->getData();
delete tail;
delete head;
tail = head = NULL;
}
else //more than 1 node
{
popped = tail->getData();
DLNode<T>* tempTail = tail->getPrev();
tempTail->setNext(NULL);
delete tail;
tail = tempTail;
}
return popped;
}
T popFront ()
{
T popped;
if (head == NULL)
{
popped = NULL;
}
else if (head == tail)
{
popped = head->getData();
delete tail;
delete head;
tail = head = NULL;
}
else
{
popped = head->getData();
DLNode<T>* tempHead = head->getNext();
tempHead->setPrev(NULL);
delete head;
head = tempHead;
}
return popped;
}
Apr 3, 2010 at 9:29pm UTC
When there's only one node left in the list, you end up deleting it both the head and the tail. Since they are both the same node, you're deleting the same node twice.
Apr 3, 2010 at 10:00pm UTC
doh... that seems to have done it. thankyou :)
Topic archived. No new replies allowed.