Sobes.tech
Junior — Middle

How is the lifetime of objects in managed heap memory determined?

sobes.tech AI

Answer from AI

In Go, the lifetime of objects in the managed heap is determined by the lifetime of references to those objects. If there are active references (variables, pointers) to an object in the heap, the garbage collector (GC) considers the object alive and does not delete it. As soon as all references to the object disappear (the object becomes unreachable), the GC marks it for deletion.

Go uses a three-generation garbage collection algorithm with reachability tracing: starting from root objects (stack, global variables), it marks all reachable objects; the rest are considered garbage.

Example:

func f() {
    p := new(int) // object in the heap
    *p = 42
    // p exists, object is alive
}
// after exiting f(), the object becomes unreachable and will be deleted by GC
How is the lifetime of objects in managed heap memory… - sobes.tech