Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete linked list

Hey I wonder about I have written a C++ linked list, where I call a destructor to go through an allocated linked list and delete every node found. However what I found is that although it goes through the linked list and delete every occurance it will still print out values. Although just some scrap values.

But shouldn't it be when I delete the linked_list it shouldn't be printable next time? I'm create a linked list by using the new, and delete when I remove the list

sorted_list::~sorted_list()
{
    // Destructor implementation
    destroy(this->first);
    cout << "Destructor called sorted_list" << endl;
}

void sorted_list::destroy(list_link* item)
{
  if (item)
  {
    destroy(item->next);
    delete item;
  }
}

print function

void sorted_list::print() {

    if(this->first)
    {
        iteratorn *traverse = new iteratorn(this->first);
        while( !traverse->iterator_end() )
        {
            cout << traverse->iterator_get_key() << " ";
            traverse->iterator_next();
        }
        delete traverse;
    }
    else
        cout << "list empty" << endl;
}
like image 683
starcorn Avatar asked Sep 25 '26 04:09

starcorn


1 Answers

When you access a destructed object, the behaviour is undefined. In fact, deleting an object doesn't clear the memory, just marks it available, so if you execute some operations on already deleted object, they may do something reasonable. But again, the object is destructed, so you must not access it.

Of course, you should not retain any pointers to the object belonging to the linked list after it's destructed, because those objects will be destructed as well.

By the way, your sorted_list::destroy is recursive, which is quite inefficient. You would need perhaps to replace it with iterative approach:

void sorted_list::destroy(list_link* item)
{
    while (item)
    {
        list_link* old = item;
        item = item->next;
        delete old;
    }
}

(And you should take into account @Roger Pate's comment and not delete this->first the second time after calling destroy(this->first);.)

like image 194
Vlad Avatar answered Sep 26 '26 16:09

Vlad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!