views:

260

answers:

6

With reference to Stack Based Memory Allocation, it is stated as "...each thread has a reserved region of memory referred to as its stack. When a function executes, it may add some of its state data to the top of the stack; when the function exits it is responsible for removing that data from the stack" and "...that memory on the stack is automatically, and very efficiently, reclaimed when the function exits"

The first quoted sentence says the current thread is responsible and second quoted sentence says its done automatically.

Question 1: Is it done automatically or by the current running thread?

Question 2: How the deallocation of memory takes place in Stack?

+2  A: 

Question 1: by automatically (and very efficiently) they mean that just by shifting a memory pointer around (cutting the top off the stack), all memory used there is reclaimed. There is no complex garbage collection necessary.

Question 2: the stack is just a contiguous chunk of memory delimited by a start and an end pointer. Everything between the pointers belongs to the stack, everything beyond the end pointer is considered free memory. You allocate and deallocate memory by moving the end pointer (the top of the stack) around. Things are much more complicated on the heap, where memory use is fragmented.

Thilo
A: 

Question 1: Yes.

Question 2: by decreasing the stack pointer, i.e. the reverse operation of allocation.

MSalters
Yes for current running thread ?
Sri Kumar
@Sri: Each thread has its own stack.
Yann Ramin
Obviously, if a thread is not running, it's neither allocating nor deallocating memory.
MSalters
A: 

ans to the question 1: yes its automatically done by the garbage collector as it is daemon process running always with the jvm. it checks for all the references and if they dont have references(or out of reach) then it will remove it from the heap.

ans to the question 2: as the local variables and method calls will be stored in stack as soon as they will be out of scope they will be removed from the stack.

GK
Stack deallocation and allocation does not require a garbage collector. Compilers have been doing this just fine for decades before the JVM came around ;)
Yann Ramin
i know stack deallocation and allocation does not require a garbage collector.
GK
A: 

The stack is managed by the compiler.

The heap is managed by a library.

Will
The heap is managed by a library? Built-in libraries of (any) programming language? If yes can you please specify the library name of your known language.
Sri Kumar
+1  A: 

You might understand more by looking at an example of a Call Stack (such as in C on many machines).

Yann Ramin
A: 

actual managing stack was due to program execution flow
which made by compiler itself