Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to the stack when exiting a method?

Tags:

java

stack

I was reading What and where are the stack and heap?. One thing I am a bit fuzzy on is what happens to the stack after a method exits. Take this image for example:

Stack

The stack is cleared upon exiting the method, but what does that mean? Is the pointer at the stack just moved back to the start of the stack making it empty? I hope this is not too broad of a question. I am not really sure what is going on behind the scenes when the stack is cleared from exiting a method.

like image 802
Evorlor Avatar asked Apr 30 '15 14:04

Evorlor


People also ask

What happens to the stack when a function returns?

At function return, the stack pointer is instead restored to the frame pointer, the value of the stack pointer just before the function was called. Each stack frame contains a stack pointer to the top of the frame immediately below.

What happens to the local variables when the method is exited?

Local variables are created on the call stack when the method is entered, and destroyed when the method is exited.

What is pushed onto the stack when a function is called?

The return address of the caller function is pushed onto the stack. This will be used to later to return control back to the calling function after the called function has terminated.

What order is data pushed onto the stack?

The data item on the top of the stack is moved to location and the stack pointer is moved to point to the next item left on the stack. So the stack is a “last in, first out” (LIFO) data structure. That is, the last thing to be pushed onto the stack is the first thing to be popped off.


1 Answers

When a method is called, local variables are located on the stack. Object references are also stored on the stack, corresponding objects are store in the heap.

The stack is just a region of memory, it has a start and end address. The JVM (java virtual machine) has a register which points to the current top of the stack (stack pointer). If a new method is called, an offset will be added to the register to get new space on the stack.

When a method call is over, the stack pointer will be decreased by this offset, this frees the allocated space.

Local variables and other stuff (like return address, parameters...) may still on the stack and will be overwritten by next method call.

BTW: this is why java stored all objects in heap. When an object would be located on the stack, and you would return the reference which points to the stack, the object could be destroyed by next method call.

like image 168
al-eax Avatar answered Sep 20 '22 03:09

al-eax