Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When does an Object gets freed?

 
Pavan Kumar Dittakavi
Ranch Hand
Posts: 106
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21115
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Madhan Sundararajan Devaki
Ranch Hand
Posts: 312
Java MS IE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I assume, you are referring to C++. The memory used by any object is released when its destructor executes sucessfully.
 
Brian Overland
author
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic