C# Stack and Heap Memory Allocation

Memory, Sweet Memory

I often times have to remind myself of the difference in memory types and how they are allocated. This is meant to be an informative piece on the difference between the stack and the heap and how each is influenced at runtime for the .NET framework and the Common Language Runtime (CLR).

Stack and Heap

Stack memory allocation occurs in the .NET framework when I value type variable is created, such as an int, or float. These are allocated in memory where for example after the completion of a method they can be disposed of and the pointer removed. Think about it using the good old stack of plates analogy or LIFO (last in first out).  These value types are often used by reference types with pointers made by the reference type to the value type.

That brings us to the next memory allocation type and that is heap(ing). Heap memory allocation is similar to what it sounds like. It’s unenforced patterning and is used by reference types, classes, objects, interfaces, string and structs all fall into this category.

How big are they though? Really…

The size of the stack is set when a thread is created. The size of the heap is set on application startup but can grow as space is needed (the allocator requests more memory from the operating system). So for example in an application with many threads there can be many stacks and usually, the heap is a shared global resource.  Garbage collection on the heap works a little differently than it does with the stack, from MSDN “When a garbage collection is triggered, the garbage collector reclaims the memory that is occupied by dead objects. The reclaiming process compacts live objects so that they are moved together, and the dead space is removed, thereby making the heap smaller. This ensures that objects that are allocated together stay together on the managed heap, to preserve their locality. ” Remember that garbage collection by the CLR can only occur on the heap.