So, I’ve written a linked list class once before, but now I need to write a Linked List Template class. Not a big deal, but I’ve been having issues with the delete operator big time.
I reused as much code as possible, but I can’t figure out why my functions to remove nodes don’t behave the same in both programs. In my template class implementation I get run time errors when trying to free the memory with delete.
Here’s the relevant code:
All nodes are added in main.cpp via the following function:
template <class T>
void LinkedList<T>::insert(T data)
{
if( pHead == NULL )
{
pHead = new LinkedList<T>( data );
}
else
{
LinkedList<T> *ptr = pHead;
while( ptr->pNext != NULL )
{
ptr = ptr->pNext;
}
ptr->pNext = new LinkedList<T>( data );
}
}
All nodes are removed in main.cpp via the following function:
template <class T>
void LinkedList<T>::removeFirst()
{
if( !pHead ) return;
else
{
LinkedList<T> *next = pHead;
pHead = pHead->pNext;
if( next != NULL)
{
delete next;
}
}
}
Here’s my destructor code:
template <class T>
LinkedList<T>::~LinkedList()
{
clear();
}
template <class T>
void LinkedList<T>::clear()
{
LinkedList<T> *ptr = pHead;
while( ptr )
{
LinkedList<T> *pTemp = ptr->pNext;
delete ptr;
ptr = pTemp;
}
pHead = NULL;
}
I get an access violation at the point where the removeFirst function tries to call delete.
I feel like the issue is simple, but almost exactly the same code worked in my non-template implementation so I wanted to see what others think before I bang my head against the wall too long.
Thanks.
You need to think clearly about the following three functions and decide whether they should remove just one item, or should clear the whole list:
As it stands, all these functions attempt to clear the whole list. The crash happens because the code in
clearattempts to delete the same things multiple times.I’m sorry to say that your code is badly flawed in many ways. You probably want the following:
Every call to
deleteleads to a call to~LinkedListwhich, currently, then attempts to clear the whole list.