I am working on coding a singly linked list in c++, and the destructor of my singly linked list is causing a segfault when it is called on a list with more than one node in it.
I am running tests on my linked list class to make sure it is functioning properly, and I am running into the problem when testing the PushFront method. I realized the destructor was causing the seg fault when I removed the delete list line from the testing function, and it ran fine without segfaulting (the PushFront testing function is just one function in a series of several testing functions to test all aspects of the linked list. With the delete line removed, the testing program calling this series of testing functions finishes execution perfectly fine, but with the delete line, it causes a segfault.
This is the destructor of the linked list (with cout statements for debugging purposes):
// CSingleLinkedList Destructor
CSingleLinkedList::~CSingleLinkedList()
{
std::cout << "In Destructor" << std::endl;
CSingleLinkedList::CSingleLinkedNode* temp = head_;
std::cout << "temp = " << temp << std::endl;
while(temp != nullptr)
{
CSingleLinkedList::CSingleLinkedNode* toDelete = temp;
temp = temp->GetNext();
std::cout << "toDelete = " << toDelete << std::endl;
std::cout << "temp = " << temp << std::endl;
delete toDelete;
}
}
This is the destructor of the linked node (which only has data members value_ (an int) and next_ (a pointer to the next CSingleLinkedNode):
// CSingleLinkedNode Destructor
CSingleLinkedList::CSingleLinkedNode::~CSingleLinkedNode()
{
delete next_;
}
This is the testing function I am running to test the PushFront function:
void TestListPushFront()
{
CSingleLinkedList* list = new CSingleLinkedList();
list->PushFront(1);
assert(list->GetFrontValue() == 1);
assert(list->GetBackValue() == 1);
assert(list->GetSize() == 1);
list->PushFront(2);
list->PushFront(3);
assert(list->GetFrontValue() == 3);
assert(list->GetBackValue() == 1);
assert(list->GetSize() == 3);
std::cout << "TestListPushFront Passed!" << std::endl;
delete list;
}
And this is the trace I see when I run the function:
TestListPushFront Passed!
In Destructor
temp = 0x55ce050332e0
toDelete = 0x55ce050332e0
temp = 0x55ce050332c0
toDelete = 0x55ce050332c0
temp = 0x55ce050332a0
Segmentation fault
Anyone have any ideas as to why this seg fault is occuring?