Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
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 Android Security Essentials Live Lessons this week in the Android 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: 18543
    
  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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: When does an Object gets freed?
 
Similar Threads
Simple question
Class loading
Reponse Commit
why i am getting OOM
Frame.dispose() - does this get rid of the frame in memory too?