A memory management model determines how a program obtains memory and makes it available for reuse. In .NET, the CoreCLR memory manager uses garbage collection: it tracks references to allocated memory and can reclaim memory when no references remain. C# code therefore does not normally need an explicit `free` call. section 1.5.3
Two memory areas help explain the difference between local execution and dynamic allocation:
- The stack holds function arguments, local variables, return addresses, and the stack frame for each active call. Too many recursive calls can exhaust it. section 10.3.4
- The heap holds dynamically allocated chunks. It is useful when an array’s size is known only at runtime; the collector can reclaim chunks that are no longer used. section 10.3.4
A runtime-sized array
The C++ array example calls `malloc`, checks whether allocation succeeded, uses the array, and calls `free`. Its C# counterpart creates `new int[n]` and passes the array to `Sum` without an explicit release. If .NET cannot allocate the memory, collection may run and the allocation is retried; if insufficient memory remains, an `OutOfMemoryException` is thrown. section 1.5.3
Listing 1.2 Creating a dynamic array in C#
public class Program
{
public static void Main()
{
int n = 4, i;
int[] p = new int[n]; #1
Console.WriteLine("Enter elements of array : ");
for (i = 0; i < n; i++) {
p[i] = int.Parse(Console.ReadLine()); #2
}
Console.WriteLine("Sum : " + Sum(p)); #3
}
private static int Sum(int[] arr)
{
int i, sum = 0;
for (i = 0; i < arr.Length; i++) #4
{
sum += arr[i];
}
return sum;
}
}
The C# listing makes the application-code difference concrete: array creation and indexed access appear, but no allocation check or `free` call does. section 1.5.3
Automatic cleanup removes a manual responsibility, not the need to understand memory costs. A PerfView GCStats example reports collection counts, total pause time, and total allocation by generation, giving concrete measures to inspect during performance work. section 1.5.3 section 10.3.4


