Doubly linked list destructor help!

My destructor for my doubly linked list is not working as intended, and I have absolutely no idea why.

My guess is because I'm failing to delink it first before deleting.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Double::~Double()
{
	Dnode *current = head;
	while (current != NULL)
	{
		Dnode *garbage = current;
		current = current->next;
	//	(current->prev)->next = NULL;
		current->prev = NULL;
		delete garbage;
	}
	current = NULL;
	delete head;
	delete tail;
}
Last edited on
I got my program to compile successfully without crashing, but is my code correct? Does it destroy all the links and avoid memory leaks/dangling pointers?

the comments are omitted segments of the program, i thought I had to de-link everything before I could delete the node?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Double::~Double()
{
	Dnode *current = head;
	
	while (current != NULL)
	{
		Dnode *temp = current;
		current = current->next;
		//	(current->prev)->next = NULL;
	//	(temp->next)->prev = NULL;
		temp->next = NULL;
//		current->prev = NULL;
		delete temp;
		head = current;
	}
	current = NULL;
	delete head;
	delete tail;
}
I got my program to compile successfully without crashing, but is my code correct?

No, it's not. Your code exhibits undefined behavior because you delete the same objects twice.

The objects pointed to by head and tail at the beginning of the destructor are deleted through the current pointer. Then they are deleted again at the end of the destructor.

1
2
3
4
5
6
7
8
9
10
11
Double::~Double()
{
    Dnode *current = head;

    while (current)
    {
        Dnode* next = current->next;
        delete current;
        current = next;
    }
}
Where in my code does it delete the same object twice?
Line 18.

Lets have a list with one node "X".
Your code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Double::~Double()
{
  Dnode *current = head;
  while (current != NULL)
  {
    Dnode *temp = current;
    current = current->next;
    temp->next = NULL;
    delete temp;
    head = current;
  }
  current = NULL;
  delete head;
  delete tail;
}

head == tail == X
current == X


temp == X
current == nullptr

delete X   ####
head == nullptr


delete nullptr
delete X   ####


What does the Dnode::~Dnode() do? I hope it does not call delete on prev and next.
Last edited on
Isn't delete head and tail deleting two separate pointers of the same object?

so is the correct condition:

while (current)?

What about everything else?
Isn't delete head and tail deleting two separate pointers of the same object?

You don't delete pointers. You delete what is pointed to.

so is the correct condition:

while (current)


while (current) and while (current != NULL) are equivalent.
Topic archived. No new replies allowed.