Head pointer null values

I have a doubly linked list, that I am working on function to clear the list, but it winds up in an infinite loop because the head pointer is supposed to be NULL when the list is empty, but it doesn't evaluate as such.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
template <class Item>
void dlist_clear(D_Node<Item> *&head_ptr, D_Node<Item> *&tail_ptr)
{
  while (head_ptr != NULL)
  {
     dlist_head_remove(head_ptr);
  }
}

template <class Item>
void dlist_head_remove(D_Node<Item> *&head_ptr)
{
  D_Node<Item> *remove_ptr;

  remove_ptr = head_ptr;
  head_ptr = head_ptr->fore();
  head_ptr->set_back(NULL);
  delete remove_ptr;
}


I'm pretty confident that the list is set up correctly with all pointers intact. However, somehow when the last node is deleted, the while loop doesn't terminate, and the loop goes into perpuity.

Can anyone see why I'm not getting a NULL value on this?

Thanks.
closed account (D80DSL3A)
Is it supposed to happen on line 16 when head_ptr = tail_ptr ? Maybe tail_ptr->fore() != NULL as perhaps you expect.

If head_ptr were to become NULL on line 16 then line 17 would cause the program to crash (due to dereference of NULL pointer there).

Can you print the list by relying on iter->fore() == NULL to stop it ?
Last edited on
That was it. I didn't see that when clearing the list, of course head_ptr eventually becomes NULL (that's the point of clearing the list), which makes line 17 crash the program. I just had to wrap line 17 in if (head_ptr != NULL) and the problem goes away.

Thanks for helping me out. I appreciate it.
Topic archived. No new replies allowed.