Click here to Skip to main content
15,897,273 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Iam having issue with the following line of code its crashing in delete. could you please the code and let me know the issue


map::iterator it = m_Map.begin();

while ( it != m_Map.end() )
{
CTest*pDTerst(it->second);
if ( pDTerst)
delete pDTerst; /crashing some times
it++;
}
m_Map.clear();

What I have tried:

I tried debugged and found the issue in the


CTest*pDTerst(it->second);
if ( pDTerst)
delete pDTerst; /crashing some times
Posted
Updated 23-Mar-16 0:06am
Comments
Philippe Mori 23-Mar-16 21:33pm    
Code above is not enough to really help you as that code might be correct or not depending on how the container is filled...

And you should use code blocks in you question to make code more readable. And also, code in "What I have tried" is the same code as above so this is redundant.

1 solution

You are creating a CTest instance on the stack and trying to delete it aftwerwards. That will of course crash because you can only delete objects that has been allocated on the heap using new.

So you would probably want to do something like this (depending on the type of the second std::pair element):
C++
delete it->second;

Note that there is no need to check for NULL because delete allows passing it (does nothing).
 
Share this answer
 
Comments
Member 11937050 23-Mar-16 6:50am    
as per you there is no need of below

if ( pDTerst)
delete pDTerst;

statement

thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900