Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 147 ยท Pointers and Memory

Garbage Collection and Memory

How Go's concurrent garbage collector works, how GOGC and GOMEMLIMIT tune it, how to read runtime.MemStats, and how cleanups, weak pointers and leaks behave in modern Go.

In Go you allocate memory freely and never free it yourself. A garbage collector (GC) runs alongside your program, finds values that nothing can reach any more, and reclaims their memory. This removes whole categories of bugs from C and C++: use-after-free, double free, and forgetting to free at all.

The collector is not magic, though. It costs CPU time, it only frees what is truly unreachable, and a program can still "leak" memory by holding on to things by accident. This lesson explains how Go's collector works at a conceptual level, the two knobs that tune it (GOGC and GOMEMLIMIT), how to look at memory from inside a program, Go 1.24's runtime.AddCleanup and weak pointers, and the most common leaks. It continues from Stack, Heap and Escape Analysis, which explains which values end up on the heap in the first place.

How the collector works

Go uses a concurrent, tri-color, mark-and-sweep collector. The words in that phrase each mean something:

  • Mark and sweep. The collector first marks every value that is reachable, starting from "roots" (global variables, and the stacks of all goroutines), following pointers. Everything not marked is garbage. Then it sweeps: the memory of unmarked values becomes available for reuse.
  • Tri-color. During marking, each object is conceptually white (not seen yet), grey (seen, but its pointers not scanned yet) or black (seen and fully scanned). Marking ends when no grey objects remain; whatever is still white is garbage.
  • Concurrent. Most of the work happens while your program keeps running, using separate GC worker goroutines. The program is paused ("stop the world") only for very short moments at the start and end of a cycle, typically well under a millisecond. When the program writes a pointer during marking, a write barrier informs the collector so it does not miss anything.
  • Non-moving and non-generational. Go's collector does not compact the heap or move objects, and it treats all objects alike. This keeps pointers stable, which is why you can hand them to other code without worry.

Because the GC follows pointers, the cost of a cycle is proportional to the amount of live memory with pointers in it, not to the amount of garbage. Fewer live pointers means less to scan, which is one reason programs that allocate many small linked objects are harder on the GC than programs that use large slices of plain values.

A value is garbage only when it cannot be reached. A variable that is still in scope but never used again will be collected (the compiler tracks liveness precisely). A value referenced from a global map that you forgot to clean will not be collected, however unused it is. That second case is a leak, and we come back to it below.

Looking at memory with runtime.MemStats

runtime.ReadMemStats fills a runtime.MemStats struct with counters. A few useful fields:

Field Meaning
HeapAlloc bytes of live heap objects plus garbage not yet swept
HeapInuse bytes in heap spans that are in use
Sys total bytes obtained from the operating system
Mallocs / Frees cumulative count of heap objects allocated / freed
NumGC number of completed GC cycles
PauseTotalNs total time the program was paused by the GC

runtime.GC() forces a full collection, which is handy in experiments but should almost never appear in production code. Because absolute numbers differ between machines and Go versions, the example below prints only comparisons that always hold.

Go Watching the heap grow and shrink

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Setting keep = nil is what made the blobs collectable. The GC does not know or care that you "meant" to be done with them; it only follows references.

For real diagnosis, run your program with the environment variable GODEBUG=gctrace=1: the runtime prints one line per GC cycle with timings and heap sizes. For a deeper look, use runtime/pprof or go tool pprof with a heap profile.

Tuning: GOGC and GOMEMLIMIT

The collector has to decide when to start a cycle. Two settings control that.

GOGC (default 100) is a percentage. After a cycle, the collector measures the live heap and starts the next one when the heap has grown by GOGC percent over that live size. With GOGC=100, a program with 100 MB live starts the next cycle at about 200 MB. Raise it (GOGC=200) and the GC runs less often, using more memory and less CPU. Lower it and you save memory but spend more CPU. GOGC=off disables the collector entirely.

GOMEMLIMIT (Go 1.19) is a soft limit on the total memory the Go runtime uses, written like GOMEMLIMIT=512MiB. As the program approaches the limit, the collector works harder to stay under it, regardless of GOGC. It is especially useful in containers with a hard memory cap. A common production recipe is GOGC=off plus a GOMEMLIMIT a bit below the container limit, though that deserves load testing. The limit is soft: if live data really exceeds it, the program keeps running (and the GC works extremely hard) rather than being killed by Go.

Both can be changed at run time through the runtime/debug package:

Go Reading and setting GC knobs in code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The default of "no limit" is the largest int64. Environment variables are the usual way to configure these; changing them from code is for tests and special tools.

Cleanups, finalizers and weak pointers

Sometimes you want to know when a value has been collected, for example to release an operating-system resource if a caller forgot to close a wrapper.

runtime.AddCleanup (Go 1.24) attaches a function to a pointer. When the object becomes unreachable, the cleanup runs, in a separate goroutine, with an argument you chose when registering it. The argument must not refer to the object, or the object would never become unreachable.

runtime.SetFinalizer is the older mechanism. It has sharp edges (finalizers can resurrect objects, a cycle of finalizers is never collected, and only one can be set per object), so the Go documentation recommends AddCleanup for new code.

Weak pointers (weak.Pointer[T], package weak, Go 1.24) refer to an object without keeping it alive. Value() returns the object or nil if it has been collected. They are the building block for caches and canonicalization maps that must not prevent collection. Together:

Go AddCleanup and a weak pointer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Cleanups run at an unspecified time, possibly never (for example when the program exits first). Never use them as a replacement for explicit Close calls. Treat them as a safety net and write defer f.Close() for anything that matters. (os.File itself uses a cleanup to close forgotten files.)

Memory leaks in a garbage-collected language

The GC cannot free what is still reachable, so leaks in Go are about reachability. Three patterns cause most of them.

Goroutine leaks

A goroutine that blocks forever keeps its stack and everything it references alive. This commonly happens when a goroutine waits on a channel that no one will ever send to or close. Each leaked goroutine costs at least a few kilobytes, and the runtime never kills it.

Go Counting leaked goroutines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The usual cure is to give every goroutine a way to stop: a done channel, a context.Context, or a closed input channel. The concurrency lessons show these patterns in depth.

Slices that pin large arrays

A slice points into a backing array. If you keep a tiny sub-slice of a huge array, the whole array stays alive. Copy the part you need if the small result will live for a long time.

Go A small slice can pin a big array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The slice internals lesson explains why this happens.

Forgotten references

Global maps, caches without eviction, registered callbacks that are never removed, time.Tickers that are never stopped, and slices of pointers where you shorten the slice without clearing the tail all keep objects reachable. When you remove an element from a slice of pointers, set the vacated slot to nil (or use slices.Delete, which clears the tail since Go 1.22) so the removed element can be collected.

Working with the collector, not against it

  • Allocate less, not "differently". Fewer, bigger, pointer-free allocations are cheapest. Reuse buffers in hot paths.
  • Do not call runtime.GC() to "help". The runtime knows better; forced collections usually make things slower.
  • Reach for GOMEMLIMIT in containers so the process collects more aggressively before the operating system kills it.
  • Measure before tuning. Use gctrace, MemStats and pprof, then change one knob at a time.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What best describes Go's garbage collector?

    Go uses a concurrent tri-color mark-and-sweep collector. It does not move objects and does not use generations or reference counts.
  2. 2. With the default GOGC=100 and 100 MB of live data after a cycle, roughly when does the next cycle start?

    GOGC is the percentage of growth over the live heap that triggers the next cycle, so 100 means the heap may roughly double.
  3. 3. What does GOMEMLIMIT do?

    It is a soft limit. The collector becomes more aggressive to stay under it, but Go does not kill your program.
  4. 4. Why can small := huge[:4] cause a memory problem if small is kept for a long time?

    A slice holds a pointer into the backing array. While any slice refers to it, the whole array is live. Copy the part you need.
  5. 5. Which is the main cause of a goroutine leak?

    A goroutine that can never proceed is never cleaned up, and it keeps its stack and referenced objects alive.

Summary

  • Go has a concurrent, tri-color, non-moving mark-and-sweep garbage collector; pauses are very short because most work runs alongside your program.
  • Memory is freed only when it is unreachable. Leaks in Go are accidental reachability: globals, caches, goroutines, pinned arrays.
  • GOGC sets how much the heap may grow before the next cycle; GOMEMLIMIT is a soft cap on total runtime memory. Both can also be set through runtime/debug.
  • runtime.ReadMemStats shows heap size and GC counts; GODEBUG=gctrace=1 and pprof help with real diagnosis.
  • runtime.AddCleanup (Go 1.24) runs a function after an object is collected; weak.Pointer (Go 1.24) refers to an object without keeping it alive. Neither replaces explicit Close.
  • Give goroutines a way to exit, copy small pieces out of large slices, and clear references you no longer need.

Next: Structs