starcorn
starcorn

Reputation: 8551

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;
}

Upvotes: 2

Views: 33006

Answers (3)

Red.Wave
Red.Wave

Reputation: 4257

Missing part is nullifying. After deleting, you must nullify the first node at least. I would nullify every node after delete.

Upvotes: 0

Kostas
Kostas

Reputation: 4186

When declaring the link, which probably looks more or less like this:

struct list_link {
    int data;
    list_link *next;
};

You could slip a destructor in:

struct list_link {
    int data;
    list_link *next;
    ~list_link() { delete next; }  // MAKE SURE NULL-TERMINATED LIST
};

This way if you want to delete the list you can simply:

delete first;

MAGIC!!

Upvotes: 0

Vlad
Vlad

Reputation: 35594

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);.)

Upvotes: 14

Related Questions