Read access error thrown when calling destructor

Apr 19, 2018 at 11:58pm
I'm currently writing a linked list project for school and I'm coming across an error when calling the destructor. My destructor looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
EmployeeList::~EmployeeList()
{
	EmployeeNode * nodeptr;
	EmployeeNode * nextNode;
	nodeptr = head;

	while (nodeptr != nullptr)
	{
		nextNode = nodeptr->next;
		delete nodeptr;
		nodeptr = nextNode;
	}
	
}


Each node is dynamically allocated when its created and in main the destructor call looks like this:

EmployeeList elist;
.
.
.
eList.~eList();

The error getting thrown is "read access violation. _Pnext was 0x650077"
Strangely enough, I have a system("pause") at the very end of my code, even after the destructor call, and the error is not thrown until I hit a key to try and close the program. Also, this is code that was provided by an instructor who said it works as intended and I have classmates who have said it works fine for them as well. Any help is appreciated, thanks!
Last edited on Apr 19, 2018 at 11:59pm
Apr 20, 2018 at 12:18am
The point of destructors is that you should not call them manually (You can, but in practice you shouldn't). They are called automatically when an object goes out of scope, or if a new'd object is delete'd.

Your issue is that the destructor is being called twice, and is trying to delete data that was already deleted.

In your main, put a block around all your relevant code except for your system("pause").

Ex:
1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
    {

        EmployeeList elist;

        // do NOT call destructor here
    }
    // destructor will get automatically called here

    system("pause");
}


However, if you want to make your destructor 2x deletable without crashing, then set head to nullptr after you set nodeptr to head.
1
2
3
4
5
6
7
8
9
10
EmployeeNode * nodeptr;
	EmployeeNode * nextNode;

	nodeptr = head;
	head = nullptr;

	while (nodeptr != nullptr)
	{
		// ...
	}

This should prevent things from being deleted twice.
Apr 20, 2018 at 12:40am
That works, thanks a lot! I didn't realize the objects called their destructor once they left a scope, that's definitely something I will remember moving forward.
Apr 20, 2018 at 1:44pm
The destructor is called whenever the object is destroyed. That's the whole point.

So, obviously, when an object that's on the stack, leaves its scope, it is destroyed, and so the destructor is called.
Topic archived. No new replies allowed.