Little drops on C# Interview questions- Stack x Heap.

ypedroo

Ynoa Pedro

Posted on July 3, 2020

Little drops on C# Interview questions- Stack x Heap.

Little drops on C# Interview Questions series

This is the first drop, the intentions behind this series are to answer with a little bit of context or examples some of most commons C# interview questions.

So Stack and Heap

First of all, both are inside the computer's RAM. The key difference is the stack is used for static memory allocation and Heap for dynamic memory.

And then you say "Ok Pedro, but this means nothing to me"

I'll answer "Calm down we're starting"

Stack

Variables allocated at the stack are available when your program is compiled hence the static allocation, the access to this memory is very fast. This memory area allows us to have stored function or methods calls in LIFO order allowing us to preserve our local variables on standby until a return occurs.

The web site that does most of the developer job Exception

Alt Text

More known as StackOverflow exception, this occurs because we have a limited memory region that is going to be used for the stack if a certain quantity of methods exhausts the quantity of memory available this will cause a StackOverflow exception. (This means that you F** up).

Heap

The heap is memory set aside for dynamic allocation which means everything stored here will be stored at runtime making the access a little bit slower, but the size limitations are equals to the size of the virtual memory. The elements here are independent of one another and can be accessed at any time. The allocation block can be also freed up anytime.

When to use each

The heap will be used for everything that you need to be stored at runtime and you don't know exactly how much data you'll allocate on the memory, on the other hand, the stack can be used for data that you'll know exactly how much data it takes and it will be stored at compile time.

Multi-thread situations

Alt Text

The stack is thread-specific and Heap application-specific.

The funny thing about situations like this, you can find each thread having its complexity and independent stacks but at the same time, they'll share the Heap.

References

If you know portuguese an awesome article going a little deeper on the stack can be found at:

https://www.eximiaco.tech/pt/2019/05/30/entendendo-a-stack-e-a-stackoverflowexception/

💖 💪 🙅 🚩
ypedroo
Ynoa Pedro

Posted on July 3, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related