Deletion causes access violation

I have a linked list and a block of code that destroys it. For no apparent reason, I'm getting an access violation. Here's my code:

1
2
3
4
5
6
7
8
9
10
11
case WM_DESTROY:
		{
		// Delete all nodes
		// Start at the base.
		NodeClass *node = baseNode;
		while (node != nullptr)
		{
			NodeClass *nextNode = node->nextNode;
			delete node;
			node = nextNode;
		}


I thought the nullptr check was supposed to prevent access violations.
I thought the nullptr check was supposed to prevent access violations.

That presumes baseNode and each nextNode were correctly set to nullptr when appropriate.

Your loop looks reasonable, but a few thoughts come to mind:

1) Does NodeClass have a destructor? If so, what does it do? If it does have a destructor and the destructor is doing cleanup of any child nodes, then your loop is going to attempt a double delete.

2) Does NodeClass's constructor properly initialize nextNode to nullptr?

3) Have you walked the node chain with a debugger? It's possible that baseNode or some node->nextNode has gotten trashed or the last node in the chain does not have a nullptr for the next pointer.

Are you using a std::list container, or have you rolled your own list container?

Topic archived. No new replies allowed.