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.
Even though the object is destroyed properly in File2.cpp, [...]
This assumption is wrong.
Obj* myobj = getMyObj();
If getMyObj
actually creates an object, it won't return a null pointer. That means the condition in the following if
is true, and then the function returns immediately.
if(myobj)
return;
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 use std::auto_ptr
if you're careful.