C# Fundamental: Stack vs. Heap

Memory Allocation (Stack and Heap)

Operating system and language runtimes such as .NET CLR divides the memory into two chunks called stack ad heap. Stack and heap act differently while allocating memory.
When we call a method, the memory required for its parameters ad variable is accommodated by the stack. When a method finishes its job, the memory is automatically released by the garbage collector for the purpose of reuse.

Stack Memory

Stack is organized like stack of boxes sitting on top of one another. When a method is called, each parameter is put into a box, first box goes first into stack then second on top of it, and so on. As in the following diagram:


Stack uses Last In First Out (LIFO) mechanism for allocating memory.


Heap Memory

Heap memory is an unorganized pile of boxes sitting in a room randomly, not like stack which stored boxes on top of each other in an order. The reference to the object is stored on stack but the actual value is stored on heap. Every box has a label that indicates whether it is in use or not. The boxes which are unreferenced the runtime marks it as not in use and empties it for future reuse.

More than one reference can point to the same object. Heap is a dynamic memory.
Dynamic memory is allocated on heap and static memory is allocated on stack.
Object type uses dynamic memory (heap) while value types uses static memory (stack).
In the below diagram, a class test object is created obj. When first line executes, it allocates a block of memory on stack to hold the reference obj but left it uninitialized this is for obj variable. When the second line executes, it initializes the variable ad allocates memory on heap.

obj reference is pointing to the object of obj on heap as below: