[HELP] Linked List memory leak, broken destructor

There is something that I am not understanding about destructors of singly linked lists. When I have my destructor set as the code below, I have memory leaks.

1
2
3
4
5
6
7
8
9
10
11
12
 LinkedList::~LinkedList()
{
	Node* temp;

	while (m_head != NULL)
	{		
		temp = m_head;
		m_head = m_head->m_next;
		temp = NULL;
		delete temp;
	}
}


Called in main like this
1
2
3
void exitLinked(LinkedList &list){
	list.~LinkedList();
}


If I change my code to
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
LinkedList::~LinkedList()
{

	Node *pDel = m_head;

	/* Traverse the list and delete the node one by one from the head */
	while (pDel != NULL) {
		/* take out the head node */
		m_head = m_head->m_next;
		delete pDel;
		/* update the head node */
		pDel = m_head;
	}
	/* Reset the head and tail node */
	m_tail = m_head = NULL;
}


Then I am given the error:
Debug Assertion Fail! Expression: "(_Ptr_user &(BIG_ALLOCATION_ALLIGNMEMT -1)) == 0" && 0
Last edited on
In a single linked list when deleting a Node, you should make sure that the remaining Nodes remain connected to the head pointer, otherwise you might get objects that you can not delete anymore (memory leak).
If I understand your current code example correctly you want to delete the first Node of the list an repeat that until there are no more Nodes, while doing so you make sure that m_head points to the new head of the list before you delete the old head Node. I would think this is a valid way to do it.

Two other ways to do this that come to mind:
- The Node objects have their own destructor that deletes the next object before the Node is actually deleted. In this case, you could just give the command to delete the head of the list.
- You use recursion (or iterating) to find the last node, delete it, return to the new last node and so on until you delete the head of the list.
The circumstances where you should call a destructor manually are very small. Most certainly this is not one of those times.

The implementation of your destructor is not what is causing your problems.

Topic archived. No new replies allowed.