Incorrect memory leak in purify?

695 views Asked by At

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.

3

There are 3 answers

10
R. Martinho Fernandes On BEST ANSWER

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.

0
CyberDem0n On
if(myobj)
   return;

After object created return proceeded and delete never performed

You need modify code:

-if(myobj)
+if(myobj==NULL)
1
AndersK On

In file1.cpp

Obj* getMyObj();

the function is kind of unsafe since the caller of the function needs to know that he must delete the object returned but it is not clear from the function that it is necessary

better is to use a smart pointer like a shared_ptr instead of the raw pointer, it would then be clear that the object returned is allocated on the heap and also how it is destroyed (if allocated).

std::shared_ptr<Obj> getMyObj();