I am trying implement a simple singly linked list and I am having a bit of trouble in my linked list deconstructor, or so I believe. The error occurs when the destructor for the Node class is called. Any ideas? Any and all help is greatly appreciated.
And that my friend is a good question. Honestly, I'm not real sure how to go about doing that. I had thought that by deleting the Node pointers (links) that the code so far would be "bomb proof", or at least to my satisfaction. However, the textbook I am currently working from is somewhat vague in parts. Any ideas on how to go about deleting the entire node as you say?
Why? Well, consider what happens on line 11. You delete a node. It's destructor will delete the node it is linked to. That nodes destructor will delete the node it is linked to, ad nauseum.
Which means that temp will be an invalid pointer.
Correct:
1 2 3 4
SLinkedList::~SLinkedList()
{
delete head; // using delete on a null pointer is perfectly fine.
}
I would say that the delete should be removed from the Node destructor and leave the linked list destructor as is. This will leave the linked list responsible for both the newing and the deleteing of Nodes.
I skimmed this too quickly to even notice that. You're right. You've set up your destructor in such a way that deleting one node will cause the deletion to chain down all the nodes after it.
And that would explain why I am getting garbage values in the debugger and pointers that are supposed to be valid, but, I have already deleted them. So, I should change my list destructor and remove the code inside the node destructor, thus basically doing what booradley60 has suggested. Also, thank you all for your time and help. I am sure that this will not be the last problem/error as I make my way through this project.