Sobes.tech
Junior — Middle

Kuidas toimub automaatne prügikoristus hallatud programmeerimiskeeltes?

sobes.tech AI

Vastus AI-lt

Automatic garbage collection (Garbage Collection, GC) in managed languages like C# is implemented through a special mechanism that tracks objects in memory and frees those that are no longer referenced.

Key principles of GC:

  • Reference tracking: GC determines which objects are reachable from root references (e.g., local variables, static fields).
  • Detection of unreachable objects: Objects without references are considered garbage.
  • Memory freeing: GC releases the memory occupied by unreachable objects.
  • Generations: To optimize garbage collection, it is divided into generations (Gen 0, Gen 1, Gen 2), allowing more frequent collection of young objects and less frequent collection of long-lived objects.

Example in C#:

class Program
{
    static void Main()
    {
        var obj = new object();
        // use of obj
        obj = null; // object becomes unreachable
        GC.Collect(); // forced garbage collector invocation (rarely used in real applications)
    }
}

This way, the programmer is freed from manually managing memory, reducing errors related to memory leaks.