Reputation: 5897
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?
Upvotes: 5
Views: 1436
Reputation: 33197
You might understand more by looking at an example of a Call Stack (such as in C on many machines).
Upvotes: 1
Reputation: 75683
The stack is managed by the compiler.
The heap is managed by a library.
Upvotes: 0
Reputation: 26428
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.
Upvotes: -1
Reputation: 180235
Question 1: Yes.
Question 2: by decreasing the stack pointer, i.e. the reverse operation of allocation.
Upvotes: 0
Reputation: 262824
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.
Upvotes: 3