5

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?

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

Question 1: Yes.

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

1 Comment

Obviously, if a thread is not running, it's neither allocating nor deallocating memory.
0

The stack is managed by the compiler.

The heap is managed by a library.

1 Comment

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.
-1

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.

2 Comments

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.