new operator and memory leak

I have methods that use

AnObject* Object::foo(...)
{
    AnObject *a = new AnObject(...);
    ....
    return a;
}

After I shut down the program the memory is leak cos "a" is not deleted. Any help to get rid of it ? I'm modifying an existing code so cannot do big changes.
ahTriAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

chensuCommented:
The caller of Object::foo is responsible for deleting the object. You may provide another member function as follows.

void Object::fooDone(AnObject *a)
{
    delete a;
}

Every call to Object::foo should come with a call to Object::fooDone.

Object o;

AnObject *p = o.foo(...);

//...

o.fooDone(p);
0
TryCommented:
I'm a little confused by your statement that, "After I shut down the program the memory is leak cos 'a' is not deleted."

When a program is terminated, the Process under which that program was running, is also terminated, and the system releases all the resources that Process had been using (under its control).  Every bit of resources (including memory) get released and are returned back to the system.  (However, I must caution you that simply terminating a Process DOES NOT remove the private memory the system allocated for the Process kernel object.  That object is NOT freed until the Process object's usage count reaches zero, which might be what you're referring to.  The Process kernel object is a SEPARATE and special object the system creates whenever it creates a Process.)

If there had been a memory leak while the program was running, it does not matter any longer once the program terminates, because the entire address space assigned to that Process gets released back to the system; even if the Process is a child Process!

Would the idea of including a destructor in your class not be something to which you'de be interested in doing?

"chensu" has given you a very good solution for taking care of this kind of memory leak WHILE THE PROGRAM IS RUNNING, but memory leaks becomes a non-issue once the program has terminated, ... absolutely and 100% a non-issue.
0
nietodCommented:
>> When a program is terminated, the Process
>> under which that program was running, is also
>> terminated, and the system releases all the
>> resources
Under windows and UNIX that is true.  But under many OSs, that is not true.

>> Would the idea of including a destructor in your
>> class not be something to which
>> you'de be interested in doing?
What does that have to do with it?

Another posibility is to use smart pointers and reference counting to avoid memory leaks.  This not basic C++ programming, but its not too difficult to do and it virtually iliminates any possiblity of memory leaks.
0
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

nietodCommented:
Chensu, why a memver function to do the delete?  the caller could do the delete directly?
0
ahTriAuthor Commented:
I run BoundsChecker on WinNT for application written in Visual C++ 5.0 and after the program shut down it report memory leak at that lines where I "new" objects. So this can be leak there plus somewhere else because I check the memory and it does lost quite an amount of resource.

Other leak is interface ...

chensu : sorry to make you miss understand but my question is not answered yet
0
jasonclarkeCommented:
You should probably ask yourself why you are returning a pointer to an object too.

If you can, the usual solution is probably to return an object by value, since that is the only way that you can guaranty correct functioning of this type of call (otherwise the client must track the usage, as described above, and cannot embed the call inside an expression:

eg. you can't do something (legitimate) like:
   
    somefunc(o.foo());

if you have to track the memory).

If your only concern is inefficiency of return by value, then you probably should not be concerned, virtually all compilers now implement return value optimisation, which makes return by value as efficient as the code you have.
(Basically the compiler is allowed to optimise away certain copy constructor calls).
0
nietodCommented:
ahTri, do you understand that every time you allocate an object (every time you use new) you must later on delete the object (using delete)?  If you do not do that, you will get a memory leak.  Does that make sense?
0
chensuCommented:
>Chensu, why a member function to do the delete?  the caller could do the delete directly?

I think that is good practise.

1. The memory allocation method is transparent to the user of Oject. The Object class might be using other memory allocation methods.

2. If it is being implemented as a DLL, the DLL uses a different heap. This will eliminate the problem. Remember faster's question?

3. It somewhat reminds the user of Object that fooDone should be called whenever there is a call to foo.
0
ahTriAuthor Commented:
nietod: yes it make sense that when you "new" have to "delete"  later on but the point is those object need to stay with the program till the end so when close the program it will be flushed anyway.

Is there any tool out there to check what's in the memory or something to integrate with Visual C++ to debug and find which part of the code cause memory leak ???
0
nietodCommented:
Chensu,

>> I think that is good practise.
I think I agree, but it might have been good to mention that is the reason, as there are other posibilities.  I say this because I wasn't sure that was the reason, so i kept readig the question to see if I missed something.

>> Remember faster's question?  
That was my question too!   and how can I forget it.  it comes up every week.


ahTri,
first of all, chensu was not wrong.  you usually should not reject an answer unless you know it is wrong.  if you need additional help, just ask.


>> find which part of the code cause memory leak
Its easy to find.  You've shown it to us.   Anyplace that has a "new" without a coresponding "delete" is a cause.  You seem to be saying that you are intentionally not calling delete, so that is the cause!

>> the point is those object need to stay with
>> the program till the end
Why?

Sometimes that thing is sort-of needed, in which case there some fancy solutions, but I suspect you don't really need to do so.
0
ahTriAuthor Commented:
nietod: yes it make sense that when you "new" have to "delete"  later on but the point is those object need to stay with the program till the end so when close the program it will be flushed anyway.

Is there any tool out there to check what's in the memory or something to integrate with Visual C++ to debug and find which part of the code cause memory leak ???
0
chensuCommented:
>but it might have been good to mention that is the reason, as there are other posibilities.

Yeah, you know, I am a little lazy sometimes.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ahTriAuthor Commented:
>> the point is those object need to stay with
>> the program till the end
Why?

Well why not ?? the pointer to that object is return when the method is call rite ? and that object stay with the program ! imagin a window object is deleted then what your application is going to run on ? If the object is a chunk of data then after you finish with that - delete is recommended to recover memory.

And as Try said those object will be fush when you close application so there is no need to delete it, I'm not intent do delete anything because not every single piece of code (of a more than million lines application) belong to me nor I understand what's is its purpose. My question at the begining is not so clear and I do apologize for that.
0
ahTriAuthor Commented:
>> the point is those object need to stay with
>> the program till the end
Why?

Well why not ?? the pointer to that object is return when the method is call rite ? and that object stay with the program ! imagin a window object is deleted then what your application is going to run on ? If the object is a chunk of data then after you finish with that - delete is recommended to recover memory.

And as Try said those object will be fush when you close application so there is no need to delete it, I'm not intent do delete anything because not every single piece of code (of a more than million lines application) belong to me nor I understand what's is its purpose. My question at the begining is not so clear and I do apologize for that.
0
nietodCommented:
>> the pointer to that object is return when
>> the method is call rite ?
right and you need to save that pointer so that you can call delete.

>> and that object stay with the program !
>> imagin a window object is deleted then
>> what your application is going to run on
I don't understand.

>> If the object is a chunk of data then
>> after you finish with that - delete is
>> recommended to recover memory.
Right.  but you're saying you don't delete the memory.

>> Try said those object will be fush when you close
>> application so there is no need to delete it
That's not exactly what he said.  His point is that you can't have a mmory leak after the program ends because the operating system will insure that the memory is freed.  But he did not say that you should not delete it.  There are other issues here.  

The first issue is that windows and other protected mode OSs will usually see to it that all memory used by an application is returned to the OS when the app finishes.  But this is not true in general.  Many OSs don't do this.  So if you rely on this, your code won't be portable

Second, all the windows OS does is make sure that the memory is returned to the OS.  That is not the only thing that the "delete" operator does.  "delete" also calls the destructor of the object to be deleted 9if there is one).  This can be very important.  if you rely on the OS doing the delete, the destructor will not be called.  The effect of this depends on the class, but important work might not get done.

Third, although in windows the memory will not be permenantly leaked, i.e. the OS will get the memory back when the program is done.   you will still get a report of the memory leak.  This report occurs because when the program terminates the RTL looks for memory that needs to be freed and reports it.  it does this BEFORE the OS reclaims the program's memory, so if you don't delete the memory the leak is going to be reported even though the OS will get the memory back!

>> I'm not intent do delete anything because
>> not every single piece of code (of a more
>> than million lines application) belong to me
>> nor I understand what's is its purpose.
You're going to have to learn.  faulure to delete that memory can have serious consequences.  We're not just talking about waisting a little memory. If there are constructors that are not being run the effects could be drastic.
0
kesonlineCommented:
One [somewhat ugly] way to handle this is to store the pointers either in an array or a linked list, and upon program termination, just flip through the array or go backwards through the linked list and run a delete. Post a comment or email me [ben@kescom.net] for simple sample code.

-Ben
0
TryCommented:
"nietod", the idea of including a destructor in a class, somewhat forces you to think about doing all the cleaning-up that has to be done relating to objects of that class and dynamic memory allocation that ought to be freed which may have been created by functions of that class.  Psychologically, it acts as a sort of reminder that forces you to deal with such matters, since you know the destructor is the place C++ designates for things opposite of what the constructor does.

Were you just testing me to see if I knew what I was talking, or was it you who wanted to know?

I'll take you on "nietod"; I'll take you on, anyday!


"ahTri", I still think "chensu" gave you the best solution!
0
nietodCommented:
>> the idea of including a destructor in a class,
>> somewhat forces you to think about doing all
>> the cleaning-up
An interesting thought, but with or without a destructor, you need to clean-up.  (The effect of ending a program while there is unfreed memory  is undefined.)  So adding a destructor that doesn't have a job to do doesn't really change anything.  Most importantly, as hyou can now see from the dialog (not at the time you posted it) ahTri has not yet grasped, the importance of cleaning up.


>> I'll take you on "nietod"; I'll take you on, anyday!
Its good to have a hobby?

>> I still think "chensu" gave you the best solution!
Yes, I think there really is only one solution, the rest are just variations on the theme.
0
TryCommented:
In your case, it's not a hobby.  IT'S A PLEASURE!!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Editors IDEs

From novice to tech pro — start learning today.