liveBook · Manning

Heap

As explained in .NET in Action, Second Edition

A heap is a runtime memory region from which programs dynamically allocate contiguous chunks of memory.

The heap holds contiguous chunks of memory allocated while a program runs. It is useful when the required size is unknown until runtime, such as when loading a file whose size may vary widely. The stack, by contrast, holds function-local variables, arguments, and return addresses in stack frames. section 10.3.4

In C++, `new int[count]` allocates an array on the heap using a runtime count, while `int arr[100]` creates a fixed-size array on the stack. A function with the right pointer can access heap memory. In .NET, the garbage collector manages application memory, collecting unused heap chunks; compaction follows collection. section 10.3.4

Listing 10.9 C# code to read numbers into a dynamic array
int[] ReadNInts(int count)
{
  int[] arr = new int[count];       #1
  for (int i = 0; i < count; i++)
  {
    arr[i] = readInt();             #2
  }
  return arr;                       #3
}

`ReadNInts` allocates an array using `count`, fills it, and returns it—a focused C# example of runtime-sized allocation. section 10.3.4

How .NET in Action, Second Edition covers it

How deep it goes
Contrasts heap allocation with stack frames and fixed-size arrays, then outlines collection and compaction without detailing collector internals.
Examples
Uses C++ and C# functions that read integers into runtime-sized arrays.
What it assumes
Builds on familiarity with functions and arrays while explaining stack frames, pointers, and heap allocation in context.
What you can do after
Evaluate/understand it by distinguishing runtime-sized heap allocation from fixed-size stack allocation and recognizing garbage collection’s role.
How it connects
Connects heap allocation to the stack, stack frames, pointers, dynamic arrays, and garbage collection.

Also explained in

Compare how 7 books explain heap →

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.