Trace roots and mark-sweep reachability
Trace roots and mark-sweep reachability
Garbage collection (GC) recovers heap storage that the running program can no longer reach. Roots include live pointers on goroutine stacks, globals and runtime structures. In Go 1.23 the collector traces reachable objects, marks them and sweeps unmarked storage for reuse. Marking is mostly concurrent with application execution; it is not reference counting. A disconnected cycle is collectible. These are implementation concepts, not a promise of immediate reclamation or a particular address layout.
package main
import ( "fmt")
func mark(g map[int][]int, roots []int) map[int]bool { seen := map[int]bool{} q := append([]int(nil), roots...) for len(q) > 0 { n := q[len(q)-1] q = q[:len(q)-1] if seen[n] { continue } seen[n] = true q = append(q, g[n]...) } return seen}func main() { g := map[int][]int{1: {2}, 2: {1}, 3: {4}, 4: {3}} m := mark(g, []int{1}) fmt.Println(m[1], m[2], m[3], m[4])}This toy graph has two cycles. Only nodes 1 and 2 can be reached from root 1. The visited set stops infinite traversal. A real collector works with typed pointers and liveness rather than integer graph labels. White means undiscovered, grey means discovered but not fully scanned, black means scanned; these colors are conceptual states.
Expected output:
true true false falseKeep an alias reachable
package main
import ( "fmt" "runtime")
type Node struct { Value int Next *Node}
var root *Node
func main() { root = &Node{Value: 7} root.Next = root alias := root root = nil runtime.GC() fmt.Println(alias.Value, alias.Next == alias) runtime.KeepAlive(alias)}Removing one reference does not remove all paths to an object. The alias remains live through the later read, so its object and cycle survive. GC does not guarantee a freed object is immediately returned to the OS. Avoid using finalizer timing or RSS as a reachability test.
Expected output:
7 trueTry it locally
Extend the graph traversal to two roots and a disconnected self-cycle; print the number of marked nodes and whether the cycle is marked.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Garbage collection 01: Trace roots and mark-sweep reachability
Check the lesson objective before moving on.
Why can an isolated cycle be collected?
What does sweeping do?