This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes C / C++ and the fly likes When does an Object gets freed? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Languages » C / C++
Bookmark "When does an Object gets freed?" Watch "When does an Object gets freed?" New topic
Author

When does an Object gets freed?

Pavan Kumar Dittakavi
Ranch Hand

Joined: Feb 12, 2011
Posts: 104

A simple question...

Let us say that an object has been allocated memory in a function. Now, when does that memory free up?

Is it something that gets freeded up as soon as the method exits or is it something that needs to be deallocated explicitly?..


P.S: This is not home work!..Im googling for answers too!.

Thanks,
Pavan.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18914
    
  40

Pavan Kumar Dittakavi wrote:A simple question...

Let us say that an object has been allocated memory in a function. Now, when does that memory free up?

Is it something that gets freeded up as soon as the method exits or is it something that needs to be deallocated explicitly?..


Well, it depends. If it is a local variable, then it will be freed when it goes out of scope. If it is a variable that has been assigned via the new operator (ie. a pointer variable), then it will be freed when the delete operator is called.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Madhan Sundararajan Devaki
Ranch Hand

Joined: Mar 18, 2011
Posts: 312

I assume, you are referring to C++. The memory used by any object is released when its destructor executes sucessfully.


S.D. MADHAN
Not many get the right opportunity !
Brian Overland
author
Ranch Hand

Joined: Sep 09, 2011
Posts: 36
Great question. It's basically been answered here....

(1) For local (that is, automatic variables, allocated on the stack), they are destroyed when the associated variable goes out of scope.

(2) If they are allocated with "new", then you must explicitly delete them.

(3) For global/static variables, the objects are destroyed when the program ends.

(4) Otherwise, all objects are supposed to be de-allocated (by default) when the program ends. I'm not sure you should always count on this, however. I would still take special care to explicitly delete objects allocated with "new."

Hope this helps,

Brian Overland
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When does an Object gets freed?