Re: Problem in deleting entries from Hash_set
??? Fri, 06 Mar 2009 13:02:17 -0800???Prafulla T?????????
Is following correct way of deleting entries from stl hashset. Will it
create any memory corruption ? One of my program uses this way and it is
crashing in strange way but purify or valgrind does not
show up anything. I am suspecting this piece of code as a problem. Can
anyone comment on it ?
for (hash_set<UserType*>::iterator hashIt = hashSet.begin();
hashIt != hashSet.end(); hashIt++)
{
UserType *pUserType = *hashIt;
hashIt++;
delete pUserType;
pUserType = NULL;
}
Anyway, according to my understanding that you are deleting the UserType
objects but not any item of your hashSet.
And the crash could came from the DOUBLE "hashIt++". As I can image your
code should either in this:
for (hash_set<UserType*>::iterator ptr = hashSet.being(); ptr !=
hashSet.end(); )
{
UserType* pUserType = *ptr;
ptr++;
delete pUserType;
// pUserType = NULL // you no longer need to set it to NULL,
since this is local pointer.
}
// You have to clear the hashSet
hashSet.clear();
Or in this:
for (hash_set<UserType*>::iterator ptr = hashSet.being(); ptr !=
hashSet.end(); ++ptr)
{
UserType* pUserType = *ptr;
// ptr++; // Since you are deleteing the UserType object which
is referenced by ptr, but ptr is still valid after you deleted the
UserType objects.
delete pUserType;
// pUserType = NULL // you no longer need to set it to NULL,
since this is local pointer.
}
// You have to clear the hashSet
hashSet.clear();
Yours,
srdgame