Middle
How is memory managed in Go? How does the garbage collector work?
sobes.tech AI
Answer from AI
Memory management in Go is automatic and implemented through a garbage collector (GC).
Memory is allocated dynamically for objects created during program execution. Go uses a reference counting and tracing (mark-and-sweep) garbage collection algorithm.
Key points:
- Memory allocation occurs via the runtime, with objects placed on the heap or stack.
- Garbage collector periodically pauses the program (stop-the-world) for a short time to determine which objects are no longer in use.
- Mark-and-sweep: GC marks all objects reachable from roots (variables, stack), then frees unmarked objects.
- Go optimizes GC pauses to minimize delays.
Example: when creating an object p := new(int), memory is allocated automatically, and when p is no longer used, GC frees the memory without programmer intervention.