How memory is managed by Stack and Heap

Taşkın Binbir
1 min readJan 2, 2022

--

Stack is used for static memory allocation and Heap for dynamic memory allocation. These are two areas that both are kept in ram.

The stack is always reserved in a LIFO (last in first out) order.

The stack is memory set aside for static allocation.

Value types (bool, int, float etc.) are on the stack.

The heap is memory set aside for dynamic allocation.

Objects are on the heap and object’s reference on the heap.

Examples:

First example:

int a = 10;

int b = a;

 +--------------+    +--------------+
| | | |
| | | |
|--------------| | |
b| 10 | | |
|--------------| | |
a| 10 | | |
+--------------+ +--------------+
Stack Heap

Second example:

string a = “Hello World”;

string b = a;

 +--------------+    +--------------+
| | | |
| | | |
|--------------| | |
b| 4000 | | |
|--------------| |--------------|
a| 4000 | | Hello World |
+--------------+ +--------------+
Stack Heap
Memory address for value "4000" in Stack area.So, object reference in stack area and value in heap area.

--

--