JavaRush /Courses /C# SELF /Memory in C#: Stack, Heap and Garbage Collector ( GC)

Memory in C#: Stack, Heap and Garbage Collector ( GC)

C# SELF
Level 65, Lesson 0
Available

1. Memory basics: Stack and Heap (Stack & Heap)

When your program runs, it gets access to memory. In the .NET context (CLR — Common Language Runtime) this memory is managed automatically and split into two main areas: the Stack and the Heap. Understanding where and how data is stored is critical for writing efficient and stable code.

Stack

Think of the Stack like a stack of plates: you always put a new plate on top and take a plate from the top. That's the LIFO (Last In, First Out) principle. The stack is very fast but size-limited.

What lives on the stack:

  • Value types: the actual values of variables declared directly.
  • References to objects: for reference types the stack holds only the address pointing to the object on the heap.
  • Method parameters: values passed into functions.
  • Local variables: variables declared inside methods.
  • Return addresses: where to return after a method finishes.

Stack memory is allocated and freed automatically and very quickly as the corresponding method finishes or a variable goes out of scope.

Example: Value types on the stack

void MyMethod()
{
    int a = 10;       // 'a' and the value 10 - on the stack
    bool flag = true; // 'flag' and the value true - on the stack
    char initial = 'Z'; // 'initial' and the value 'Z' - on the stack

    // ...
} // When MyMethod finishes, 'a', 'flag', 'initial' are removed from the stack.

Example: References on the stack

class MyObject { }

void AnotherMethod()
{
    MyObject objRef; // 'objRef' (reference) - on the stack. The object itself is not created yet.
    // ...
} // When AnotherMethod finishes, 'objRef' (reference) is removed from the stack.

Heap

The Heap is a much larger and more flexible area of memory. There's no strict LIFO order here; data can be placed anywhere there's free space. The heap is used for larger and/or longer-lived objects.

What lives on the heap:

  • Objects of reference types: class data, arrays, strings — created with new.
  • Nested value types: if a value type (struct) is a field of a reference type (class), it's stored inside the object on the heap.

Heap memory is managed automatically by the GC (Garbage Collector).

Example: Class objects on the heap

class Person { public string Name; public int Age; }

void CreatePerson()
{
    Person p = new Person(); // Person object - on the heap. 'p' (reference) - on the stack.
    p.Name = "Alice";        // The string "Alice" (also an object) - on the heap.
    p.Age = 30;              // 30 (int, value type) - inside the Person object on the heap.
    // ...
} // When CreatePerson finishes, 'p' (reference) is removed from the stack.
  // The Person object on the heap becomes unreachable and is eligible for garbage collection.

Example: Arrays on the heap

void ProcessArray()
{
    int[] numbers = new int[5]; // An array of 5 ints - on the heap. 'numbers' (reference) - on the stack.
    numbers[0] = 10;            // The element 10 is part of the array on the heap.
    // ...
} // The array will be cleaned up by GC when there are no references to it.

2. Garbage Collection

Heap memory is managed automatically thanks to the GC. This is one of .NET's key features that saves you from manual memory freeing (a common source of leaks in non-garbage-collected languages).

Purpose and how it works

The main goal of the GC is to automatically free memory occupied by heap objects when they are no longer used by the program.

  1. Object creation: when you use new the CLR allocates space on the heap.
  2. Tracking references: the GC tracks active references; an object is "reachable" if there is a reference to it from the stack, a static field, or another reachable object.
  3. Determining "garbage": if there are no references — the object is "unreachable" and considered garbage.
  4. Collection: when needed the GC marks reachable objects and frees the memory of unreachable ones.
  5. Compaction: to reduce fragmentation, remaining objects can be moved to form contiguous regions.

Generations in GC (Generational GC)

The GC uses generations because most objects "die young":

  • Generation 0 (Gen 0): new objects; collections are frequent and fast.
  • Generation 1 (Gen 1): survivors of Gen 0; collections are less frequent and take longer.
  • Generation 2 (Gen 2): long-lived objects; collections are the rarest and most expensive.

When does GC run?

  • Lack of free memory for a new allocation.
  • Periodic checks during idle time.
  • Explicit (generally not recommended) call to GC.Collect().

GC performance

A GC run can cause short pauses because user code execution is suspended. Excessive creation of short-lived heap objects results in more frequent collections and reduced performance.

Example: Object becomes unreachable

class DataBlock { public byte[] Data; public DataBlock() => Data = new byte[1024 * 1024]; } // 1 MB of data

void AllocateAndLose()
{
    DataBlock block1 = new DataBlock(); // block1 object on the heap, 'block1' reference on the stack

    // ... some code ...

    block1 = null; // Now there are no active references to the DataBlock object. It became unreachable.
    // At this point GC HAS NOT YET REMOVED it, but it is a candidate for collection.

    // Calling GC.Collect() here (only for demo, don't do this in production!)
    Console.WriteLine("Calling GC.Collect()");
    GC.Collect(); // GC may (but is not guaranteed to) free memory now
}

AllocateAndLose();
// When AllocateAndLose finishes, the 'block1' reference is removed from the stack,
// and the DataBlock object on the heap becomes unreachable and eligible for collection.

3. Managing unmanaged resources

The GC manages .NET "managed" memory. But there are unmanaged resources that live outside GC control and require explicit release:

  • File descriptors (open files).
  • Network sockets.
  • Window/graphics handles (e.g., GDI+).
  • Memory allocated from the OS (e.g., via P/Invoke).

Finalizers

A finalizer is a special method that performs last-resort cleanup of unmanaged resources before the GC removes an object. The syntax looks like a constructor but with a tilde:

class MyClassWithFinalizer
{
    ~MyClassWithFinalizer() { /* Releasing unmanaged resources */ }
}

The GC invokes finalizers unpredictably, with delay, on a separate finalizer thread. Downsides: unpredictability and overhead (objects with finalizers require two passes). So finalizers are a "safety net", not the main cleanup mechanism.

Example: Finalizer as a "safety net"

class UnmanagedResourceHolder
{
    private bool _resourceReleased = false;

    // Simulate an unmanaged resource
    public UnmanagedResourceHolder() => Console.WriteLine("Resource created.");
    
    public void ReleaseResource()
    {
        if (!_resourceReleased)
        {
            Console.WriteLine("RESOURCE RELEASED explicitly.");
            _resourceReleased = true;
        }
    }

    // Finalizer - called by GC as a last resort
    ~UnmanagedResourceHolder()
    {
        Console.WriteLine("Finalizer CALLED (resource was NOT released explicitly).");
        ReleaseResource(); // Attempt to release the resource
    }
}

The IDisposable interface

IDisposable is the preferred mechanism for explicit resource release. It contains one method: void Dispose(). It's common to implement a pattern where Dispose() is safe to call multiple times and suppresses the finalizer via GC.SuppressFinalize(this).

Example: Implementing IDisposable

using System.IO;

class MyFileWriter : IDisposable
{
    private StreamWriter _writer;
    private bool _disposed = false;

    public MyFileWriter(string path)
    {
        _writer = new StreamWriter(path, true);
        Console.WriteLine($"File '{path}' opened.");
    }

    public void WriteLog(string message) => _writer.WriteLine(message);

    // IDisposable implementation
    public void Dispose()
    {
        Dispose(true); // Call main Dispose logic
        GC.SuppressFinalize(this); // Tell GC that finalizer is not needed
        _disposed = true;
    }

    // Protected virtual method for the common Dispose pattern
    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
            {
                // Free managed resources
                _writer?.Dispose();
            }
            // Free unmanaged resources (if any)
            Console.WriteLine("File CLOSED via Dispose.");
        }
    }

    // Optional finalizer as a "safety net"
    ~MyFileWriter()
    {
        Console.WriteLine("File CLOSED via finalizer (Dispose() was not called).");
        Dispose(false); // Call Dispose indicating this is not an explicit call
    }
}

The using statement

The using statement is syntactic sugar that guarantees Dispose() will be called when the object goes out of scope, even if an exception occurs. It's the recommended way to work with objects that implement IDisposable.

Example: Automatic cleanup with using

// Using MyFileWriter from the example above
void ProcessFile(string fileName)
{
    // The MyFileWriter object will be automatically disposed after the using block
    using (var writer = new MyFileWriter(fileName))
    {
        writer.WriteLog("First line.");
        writer.WriteLog("Second line.");
        // Even if an exception happens here, Dispose() will still be called
    } // writer.Dispose() is called automatically here

    Console.WriteLine("Using block finished, file closed.");
}

ProcessFile("testlog.txt");
// In this case the MyFileWriter finalizer won't be called because Dispose() was called explicitly.

Understanding these concepts is key to writing performant, reliable, and scalable C# applications.

2
Task
C# SELF, level 65, lesson 0
Locked
Difference between stack and heap
Difference between stack and heap
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION