CodeBlanks Logo Icon CodeBlanks

What is GC?

Learn the main goal of the garbage collector.

What is GC?

The garbage collector (GC) automatically reclaims heap memory the program can no longer reach. Go has no free call; if no root (globals, goroutine stacks, registers) can reach an object, the GC collects it.

func yeni() *Dugum {
    d := &Dugum{}  // escapes to the heap
    return d
}

p := yeni()
p = nil  // no longer reachable → collected at the next GC

Go's GC is concurrent and low-latency: pauses are usually under a millisecond.

Stack or heap?

Only heap memory loads the GC. Values that stay inside a function and don't escape live on the stack and are freed for free when the function returns. The compiler decides where each goes with escape analysis. Fewer heap allocations = less GC work.

Practice GC count

Read NumGC with runtime.ReadMemStats, call runtime.GC() and read it again. Print whether the count increased (after > before).

Starter code

main.go
package main

import (
    "fmt"
    "runtime"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "runtime"
)

func main() {
    var a, b runtime.MemStats
    runtime.ReadMemStats(&a)
    runtime.GC()
    runtime.ReadMemStats(&b)
    fmt.Println(b.NumGC > a.NumGC)
}

Expected output

true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is required for an object to be collected?

  • The function must have returned
  • It must be unreachable from every root Correct answer
  • It must be marked with free
  • It must have been assigned nil

Explanation: The GC looks at reachability; assigning nil only makes the object unreachable if it was the last reference.

2 Trigger GC manually

Question
runtime.____()  // genellikle gerekmez
Answer
runtime.GC()  // genellikle gerekmez

Explanation: runtime.GC() forces a collection cycle; it is rarely used outside measurements and tests.

3 Memory concepts

Term Meaning
Root Global and stack references
Heap Memory the GC manages
Stack Freed with the function
Unreachable object Gets collected

All lessons in Expert