Reputation: 56479
There is a map which maps int
to Test*
. All Test*
pointers are allocated before assigning to the map. Then, it delete
s 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 delete
ing them in the loop. How can it fixed?
Second question is, does it correctly delete
the allocated pointers?
Upvotes: 1
Views: 2277
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