I ran purify on my code which runs in Solaris and it shows lot of memory leaks. But I checked the code and most of the leaks seem to be invalid.
For eg,
File1.cpp
Obj* getMyObj()
{
Obj* obj = NULL;
if(condition)
{
obj = new Obj(); //Purify is reporting leak here
//Fill obj
}
...
return obj;
}
File2.cpp
void myfunc()
{
Obj* myobj = getMyObj();
if(myobj == NULL)
return;
...
...
delete myobj; //The object is deleted here
}
Even though the object is destroyed properly in File2.cpp
, why is purify reporting leak in File1.cpp
?
EDIT
The NULL check was just a typo, I corrected it.
This assumption is wrong.
If
getMyObj
actually creates an object, it won't return a null pointer. That means the condition in the followingif
is true, and then the function returns immediately.No further code executes in that function, so it's never destroyed.
I recommend the use of smart pointers instead of this kind of manual management, as this kind of errors just goes away. With C++11 you can use
std::unique_ptr
, otherwise you can usestd::auto_ptr
if you're careful.