liveBook · Manning

Stack

As explained in .NET in Action, Second Edition

A stack is a runtime memory region that stores function-local variables, arguments, and return addresses using call-order allocation.

The stack records active method calls. Each call adds a stack frame; when the method finishes, its frame is removed and execution returns to its caller. A frame keeps the information needed for that return, including local variables, arguments, and a return address. section 10.3 section 10.3.4

Reading a call stack

If CheckJokes calls a Newtonsoft test method, which calls DeserializeObject, the stack runs from CheckJokes at the bottom to DeserializeObject at the top. A profiler can inspect an executing thread’s frames and match them to symbols such as assembly, class, and method names. That makes a stack useful for connecting CPU activity to the code that led to it. section 10.3

The stack is distinct from the heap. A called function gets its own frame rather than manipulating its caller’s stack variables. The heap holds dynamically allocated memory; code with an appropriate reference or pointer can access it. This distinction matters when an array’s size is known only at runtime. section 10.3.4

A runtime-sized array

In C#, `int[] arr = new int[count];` creates an array whose length comes from `count`. The method can fill it and return it. Do not treat the array’s dynamically allocated storage as though it were the method’s stack frame: the frame is removed when the call completes, while the returned array remains available to its caller. section 10.3.4

Recursion makes stack growth visible: every invocation needs another frame. Too many recursive calls can exceed the stack’s maximum size and cause a stack overflow. section 10.3.4

A representation of the stack frames when the DeserializeObject method is executed

The frame diagram makes the order of nested calls visible while DeserializeObject is executing. section 10.3

How .NET in Action, Second Edition covers it

How deep it goes
Explains frames, call-and-return behavior, stored data, and overflow without detailing byte-level frame layout.
Examples
Uses a nested method-call diagram and C++ and C# runtime-sized array listings.
What it assumes
Assumes familiarity with method calls and arrays while explaining stack frames and their memory role.
What you can do after
Diagnose/debug with it by interpreting profiled call frames and recognizing recursion-driven stack overflow.
How it connects
Links stack frames to recursion, stack traces, CPU profiling, the heap, and garbage collection.

Also explained in

Compare how 14 books explain stack →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.