Wednesday, 12 February 2014

Stack Memory

Stack is a special region in computer memory, that stores temporary variables like local variables, parameters, function calls etc.,

Stack works in last in first out (LIFO) order. Whenever a new local variable initialized inside a function, it is pushed onto the stack, when the function finished execution, all the local variables pushed by that function onto the stack are removed from the stack.

CPU organizes the stack memory for function calls, local variables creation, recursion.

CPU organizes stack memory so efficiently, so reading from and writing to stack variables is very fast.

There is a limit on the size of variables that can be stored on the stack

The default stack size depends on the platform

Example Below are some default stack sizes, These may change from version to version and platform to platform

Platform Default
Windows IA32 64 KB
Linux IA32 128 KB
Linux x86_64 256 KB
Windows IA64 320 KB
Windows x86_64 128 KB
Linux IA64 1024 KB (1 MB)
Solaris Sparc 512 KB

Example Of Recursion
class Stack{
 static void print(int n){
  if(n==0) return;
  else{
   print(--n);
   System.out.println(n);
  }
 }

 public static void main(String args[]){
  print(4);
 }
}
   
Output
0
1
2
3


Some Points to Remember
1. In java, you can never put an object on stack, only object reference can be stored on stack. Objects always stored in heap
 

Lambda Expression that computes a value                                                 Increase Stack Size                                                 Home

No comments:

Post a Comment