BeTheSame
BeTheSame

Reputation: 13

C++ : memory leak for just constructor

I am creating a class from a huge external package. And I ran:

Foo* foo = new Foo("bar", 100);
if(!foo)
{
    delete foo;
}

with

Foo::Foo(TString bar, int num)
{
    setnull();
}

and the setnull() is just setting every class pointers in NULL, like:

void Foo::setnull()
{
    fooArray = NULL
    ...
}

and the destructor

Foo::~Foo()
{
    if(fooArray != NULL)
            delete[] fooArray;
    ...
    setnull();
}

There are actually a lot of pointers to the classes from the external packages setting to NULL as well in the .hh file. As a result I got:

definitely lost: 332 bytes in 1 blocks

I also get indirect lost from adding in constructor:

fooArray = new (nothrow) bool [5];
    if (fooArray == NULL)
    {
        cout << "ERROR: memory could not be allocated"<<endl;
    }
fooArray[0] = 0;    

with

indirectly lost: 26 bytes in 2 blocks

(one other thing, somehow the title for Stackoverflow tends to eat up the "++" sign)

Upvotes: 0

Views: 105

Answers (2)

juanchopanza
juanchopanza

Reputation: 227410

As has been pointer out in other answers, this logic is wrong:

if(!foo)
{
    delete foo;
}

But you don't have to perform the check anyway: calling delete in a null pointer is a no-op and completely safe. So you could simplify your code to

Foo* foo = new Foo("bar", 100);
delete foo;

Of course, the simpler, safer option would be

Foo foo("bar", 100);

Upvotes: 2

Joachim Isaksson
Joachim Isaksson

Reputation: 180917

Foo* foo = new Foo("bar", 100);
if(!foo)
{
    delete foo;
}

You're only deleting foo if it's NULL, if new returns an object, you won't delete it.

Upvotes: 4

Related Questions