masoud
masoud

Reputation: 56479

Delete pointers from a map

There is a map which maps int to Test*. All Test* pointers are allocated before assigning to the map. Then, it deletes pointers of map and set them to null. After that, It checks validity of one, and it is supposed to be null. But, one is not null.

#include <QString>
#include <QMap>
#include <QDebug>

class Test {
    QString name;
public:
    Test(const QString &name) : name(name) {}
    QString getName() const { return name; }
};

int main() {
    QMap<int, Test*> map;

    Test *one = new Test("one");
    Test *two = new Test("two");
    Test *three = new Test("three");

    map.insert(1, one);
    map.insert(2, two);
    map.insert(3, three);

    for (auto itr = map.begin(); itr != map.end(); itr++) {
        Test *x = *itr;
        if (x) {
            delete x;
            x = 0; // ** Sets null to the pointer ** //
        }
    }

    if (one) // ** Here one is not 0 ?! ** //
        qDebug() << one->getName() << endl; // ** And then here crashes ** //
}

I think, I missed something when deleteing them in the loop. How can it fixed?

Second question is, does it correctly delete the allocated pointers?

Upvotes: 1

Views: 2277

Answers (2)

user362638
user362638

Reputation:

Easiest way to delete all would be:

qDeleteAll(map);

Upvotes: 3

Some programmer dude
Some programmer dude

Reputation: 409176

In the loop, the variable x is a local pointer only inside the loop. When you set that to NULL you don't actually set any other pointers to NULL.

What you should to is to set the reference returned by dereferencing the iterator to NULL:

*itr = nullptr;

This will make the pointer in the map be NULL, but the other pointers will still be pointing to a now deallocated memory area.


When you have two pointers, it kind of looks like this:

+-----+
| one | ---\
+-----+     |     +---------------+
             >--> | Test instance |
+-----+     |     +---------------+
|  x  | ---/
+-----+

If you set one of the pointers it looks like this:

+-----+
| one | ---\
+-----+     |     +---------------+
             >--> | Test instance |
+-----+           +---------------+
|  x  | 
+-----+

The variable x is NULL but the variable one still points to the object. And if the object has been deleted then dereferencing that pointer you will cause undefined behavior.

Upvotes: 5

Related Questions