0

I have a small question:

Foo *myFoo;
myFoo = new Foo(anotherFoo);     // some deep copy of another object
myFoo = new Foo(yetAnotherFoo);  // another deep copy of yet another object

Is this a memory leak and if yes, how can I avoid it properly? The situation in my program is, that 'myFoo' is a class member and I want to use it as a "one and only" storage-object for a deep copy of some other object from time to time (because the copied object is modified afterwards and I need the initial object for later comparison).

I have tried a simple workaround like:

// within a class method of the same class
if (myFoo!=NULL) delete myFoo;
myFoo = new Foo(fooToStore);

but this crashes my program as soon as the destructor is called. I am not sure if my (non-trivial) destructor is a bit buggy (different problem not to discuss here) or if deleting a class-member object via delete within a class method is forbidden in general.

Thanks a lot for your time and help - appreciate it! Mark

1
  • Sidenote: there is no need to check if myFoo is NULL before calling delete, delete handles NULL values correctly.
    – larsmoa
    Oct 4, 2011 at 10:39

3 Answers 3

4

Not deleting the result of a new expression before re-assigning the pointer surely causes a memory leak. The explicit-delete solution should work, but what you really want is a smart pointer-typed member, e.g. a scoped_ptr<Foo>.

That might (or might not) magically solve your destructor problem as well.

2

Yes, it is a memory leak, because the second assignment to myFoo causes the first Foo you allocated to become inaccessible. Deleting myFoo between successive allocations is the correct thing to do. Note that you don't need to check for a null pointer: delete takes care of that. It looks very likely that you have some problem in Foo's destructor.

2
  • ... and may be even constructor, if the destructor does a delete of an uninitialized member pointer. Oct 4, 2011 at 11:58
  • Thanks for your help! I will have a closer look at both the constructor and destructor. Regards, Mark
    – user911995
    Oct 4, 2011 at 13:45
0

I assume that "but this crashes my program as soon as the destructor is called" means that main class destructor invoke 'myFoo'delete.

Don't forget to initialize 'myFoo' to null in main class constructor, this will prevent crashes on main class destructor if no instances of 'myFoo' are created.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.