Sunday, September 23, 2012

A note on Stack and Heap

  • Stack-memory and Heap-memory are physically the same.
  • The RAM may be used as stack memory when running one program and later used as heap memory when running some other program.
  • The difference is in how they are used.
Difference between Stack vs Heap memory:
 

Stack:
  • Often a function or method calls another function which in turn calls another  function etc.
  • The execution of all those functions remains suspended until the very last function returns its value.
  • All the information required to resume the execution of these functions is stored on the stack.
  • In particular, local variables are stored on the stack.
  1. Local variables are often stored for short amounts of time while a function/method block uses them to compute a task.
  2. Once a function/method has completed its cycle, the space on the stack used by all local variables is freed.
  • This chain of suspended function calls is the stack, because elements in the stack (function calls) depend on each other.
  • The stack is important to consider in exception handling and thread executions.

Heap:
  • The heap is simply the memory used by programs to store global variables. or All global variables are stored in heap memory.
  • Element of the heap (variables) have no dependencies with each other and can always be accessed randomly at any time.
  • All variables dynamically created by the program with "new()" or "malloc()" or similar commands are also stored on the heap.
  • In some programming languages, all instances of an object, including all the attributes of that instance, are stored on the heap (java).
  • In those programming languages, local variables of a function that have object type are implemented as creating the new object on the heap, and storing a reference to that object in the local variable, which is on the stack.
  • When that function exits, the heap memory used by each local variable that has object is freed, and then all the stack used by that stack is freed.

Similarties:
  • Both are used for providing memory to a program at run time.
  • both reside in main-memory (RAM)
  • both are datastructure (used to organised data)

No comments:

Post a Comment