Is it possible to traverse a linked list with its node head in its destructor?

This may seem like a silly question, but the reason I'm asking for is because I have this destructor:

list::~list()
{
    for (node* next = headByName->nextByName; headByName; headByName = next)
    {
        delete headByName;
    }
}

and valgrind still says i have a memory leak. Therefore, I assume that my real question is: is my destructor corrupted incorrectly, or is it just bad to destroy a list by going through its head with a node?

+4
source share
2 answers

Your code does not fit.

  • You never change next, therefore it headByNamedoes not change after the first iteration.
  • If headByName is nullptrbefore the start of the loop, you can dereference nullptr in your initialization.

Try the following:

list::~list()
{
    while (headByName)
    {
      node* next = headByName->nextByName;
      delete headByName;
      headByName = next;
    }
}
+3

, for, , , , for:

for(node* next; headByName; headByName = next)
{   next = headByName->nextByName;
    delete headByName;
}
+3

Source: https://habr.com/ru/post/1611046/


All Articles