Mark Ang
Mark Ang

Reputation: 149

does leaving pointers in functions cause memory leaks?

Suppose I have a function or class that maintains some pointers to other data objects, like so:

class MyObject {
    ...
    AnotherObject* o1, *o2;
    SomeObject* s1, *s2;
    ...
}

int main() {
    ...
    MyObject mo1 = new MyObject();
    ... // do stuff with mo1
    delete mo1;
}

Suppose they are assigned valid pointer values from elsewhere during/after initialization.

When I destroy the MyObject object after assigning those pointers inside, can a memory leak result if I do not null the pointers during destruction like so?:

MyObject::~MyObject() {
    o1 = nullptr;
    o2 = nullptr;
    ...
}

Thanks.

Upvotes: 1

Views: 1311

Answers (3)

Marinos K
Marinos K

Reputation: 1829

No it won't cause a memory leak. Note however that this:

MyObject mo1 = new MyObject();
// do stuff with mo1
delete mo1;

will result in a memory leak if do stuff with mo1 throws an exception (which could be the case if it comprises references to nullptr). Therefore it's advisable not to use naked pointers like you do but smart pointers instead - this way RAII guarantees that your pointer will be deleted.

Upvotes: 2

Humam Helfawi
Humam Helfawi

Reputation: 20264

No it would not. Memory leak happens because of a non-deleted memory which was allocated using new. Nulling a pointer is just a way to check it later if it was deleted or not and it has nothing to do with memory leak.

On the other hand, dealing with memory manually is not a the best way to achieve what you want. Smart pointers are exist (std::shared_ptr, std::unique_ptr...). You should have a look on them.

Upvotes: 0

H. Guijt
H. Guijt

Reputation: 3365

It sounds like you come from a Java background, where setting pointers to null is necessary to allow the garbage collector to reclaim other objects. If so, the answer is simple: no, that's not how it works in C++. Setting a pointer to null has no bearing whatsoever on memory usage, and there is no garbage collector anyway that could reclaim any memory.

Instead you are supposed to consider ownership. Most objects have one specific owner; once that owner is deleted, so are its owned objects. This is most conveniently modelled using unique_ptr instead of raw pointers. For objects that have more complex ownership, there is shared_ptr and weak_ptr.

Once again, there is no garbage collector, so any time you use new to create an object, somehow, somewhere there must be a corresponding delete. The easiest way to ensure such deletes are not forgotten is to use unique_ptr.

Also be wary of using new too often. Your mo1 object can be allocated on the stack without any problem: it's lifetime is limited to one function (main), so why not use simply allocate it as MyObject mo1; - that's enough, no need to new or delete anything.

Upvotes: 1

Related Questions