The Stack And The Heap

The stack and the heap

A running program requires its data to be stored in the memory. How much memory it will require to store the data, and where and how the data will be stored totally depends on its type. A running program uses two regions of memory- stack and heap.
 
The Stack

The stack is an array of the memory that acts as Last-In, First-Out (LIFO) data structure. It stores several types of data for example,
  • It stores values of certain types. 
  • It stores program's current execution environment. 
  • Parameters passed to the methods. 
System takes care of all stack manipulation. You do not need to do any thing with it explicitly.
 
Facts about stack 

The general characteristics of stack are given below.
  • The data can be added to and removed only from the top of the stack.
  • Adding a data on the top of the stack is called pushing the item onto the stack.
  • Removing an item on the top of the stack is called popping the item from the stack.
The heap 

The heap is an area of the memory, where chunks are allocated to store certain kinds of data objects. Unlike the stack, the data can be stored and removed in any order from the the Heap.
 
Although your program can store the items in the Heap, it cannot explicitly delete them. Instead the CLR's Garbage Collector (GC) automatically cleans up unneeded heap objects when it determines when your code can no longer access them.
Ebook Download
View all
Learn
View all