skipnothing/.NET Platform

Stack vs Heap

Declare `struct Point` as a local and it sits in one place; make it a field of a class and the identical bytes sit somewhere else entirely. The type never changed, only its address did.

  • A value's home is decided by how long it must live, not by whether you wrote struct or class.
  • A variable that points at an object and the object itself are two separate things in two separate places.
  • One region frees its space the instant a method returns; the other makes you pay a cleanup bill later.
BUILDS ON
01

The call stack, frame by frame

Three methods call each other in a line:

int Outer()  => Middle();
int Middle() => Inner();
int Inner()  => 42;

When Outer calls Middle, the program reserves a block for Middle's parameters and locals, then stacks another block for Inner on top. Each block is a stack frame, and they pile up in call order on a per-thread region called the call stack. When Inner returns its frame is gone; when Middle returns its frame is gone too. The order is strict last-in-first-out: the most recent call is always the next to leave.

A frame is not cleared field by field. The program keeps one pointer to the top of the call stack, and a return just moves that pointer back down past the whole frame. Every local in it disappears in that one move, which is why reserving and releasing here costs almost nothing.

This is a different stack from the one the previous topic disassembled. That evaluation stack was a per-method scratch space for individual opcodes, alive only inside one method's body. The call stack holds whole frames, one per active call, and spans the entire chain of methods running on the thread right now. Same word, two layers: keep them apart and the rest of this topic stays clear.

FRAMES PILE UP AND POP ON RETURN

Keep going, sign up to unlock the rest

4 more parts in this topic, plus 25+ more topics in .NET Platform.

Sign up, it's freeSee the full .NET Platform
Memory & the Type System0/6#5 Assemblies & NuGet
#7 Value Types vs Reference Types