Sitemap
Albatros

Albatros

I explain how emerging technology changes the products you use, the money you spend, and the data you share. Evidence-led, practical, no hype.

Member-only story

C# Stack vs Heap Memory

4 min readDec 21, 2022

--

Press enter or click to view image in full size
Stack vs Heap

In C#, memory is divided into two regions: the stack and the heap. Understanding the differences between the stack and the heap is important for writing efficient and correct C# code.

Stack Memory

The stack is a region of memory that is used to store local variables and function call information. It is called a “stack” because it behaves like a stack of items, with the most recently added item being the first one to be removed (last in, first out).

Each time a function is called, a new block of memory is allocated on the stack for that function’s local variables and parameters. When the function returns, this block of memory is deallocated and the stack pointer moves back to the previous function’s block of memory.

One important property of the stack is that it is very fast to allocate and deallocate memory from it. This is because the stack has a fixed size and the memory is allocated and deallocated in a last-in, first-out manner.

However, the stack has a limited size and can only store a finite amount of data. If the stack grows too large, it can cause a stack overflow, which can lead to a crash or other unpredictable behavior.

Heap Memory

The heap is a region of memory that is used to store objects. It is called a “heap” because it…

--

--

Albatros
Albatros

Written by Albatros

I explain how emerging technology changes the products you use, the money you spend, and the data you share. Evidence-led, practical, no hype.