I am trying to delete a linked list using the destructor.
But this code is giving a segmentation fault:
~Node()
{
Node *current = this ;
Node *previous = NULL;
while(current != NULL)
{
previous = current;
current = current->next;
delete previous;
previous = NULL;
}
}
What am I doing wrong here?
You should exclude the current node from the delete
operator, as the code is already a response to such a delete
. Doing it again is like running in circles.
So modify your code to this:
~Node()
{
Node *current = this->next; // exclude current node
Node *previous;
while (current != NULL)
{
previous = current;
current = current->next;
previous->next = NULL; // avoid the delete below to propagate through list.
delete previous;
}
}
There is no need to set previous
to NULL
, since it will run out of scope. But it is needed to detach previous
from its successors, so to avoid the the destructor will follow that chain again.
This code assumes that this
is the first node of the list, which would be the natural thing to execute delete
on. If for some reason you would execute delete
on a node somewhere in the middle of a list, with the aim to discard the whole list, then you would need to repeat the above loop also for the nodes that precede the current node.