How memory is managed by Stack and Heap

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.

--

--

--

Computer Engineer, Software Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Taşkın Binbir

Taşkın Binbir

Computer Engineer, Software Developer

More from Medium

.NET Unit Testing Best Practices

Using Channels for Asynchronous Queuing in C#

NET5 Exception Handling Made Easy

Design Patterns — Adapter .NET