go runtime ai_generated true

runtime error: invalid memory address or nil pointer dereference

ID: go/nil-pointer-dereference

Also available as: JSON · Markdown
96%Fix Rate
97%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
121 active
1 active

Root Cause

Attempting to dereference a nil pointer, often from unchecked error returns.

generic

Workarounds

  1. 96% success Add nil checks before dereferencing: if ptr != nil { ... }
    if user != nil {
      fmt.Println(user.Name)
    }
    // For nested pointers:
    if resp != nil && resp.Body != nil {
      defer resp.Body.Close()
    }

    Sources: https://go.dev/doc/effective_go#errors

  2. 94% success Use the comma-ok idiom for map lookups and type assertions
    // Map lookup:
    val, ok := myMap[key]
    if !ok { return fmt.Errorf("key %q not found", key) }
    // Type assertion:
    str, ok := iface.(string)
    if !ok { return fmt.Errorf("expected string, got %T", iface) }

    Sources: https://go.dev/doc/effective_go#interface_conversions

  3. 90% success Return concrete types with zero values instead of nil pointers
    // Instead of returning *Config (can be nil):
    func NewConfig() Config {
      return Config{Timeout: 30 * time.Second, Retries: 3}
    }
    // Use value receivers on the zero value:
    var c Config  // safe to use immediately

    Sources: https://go.dev/doc/effective_go#pointers_vs_values

Dead Ends

Common approaches that don't work:

  1. Using recover() to catch all nil pointer panics 75% fail

    Masks bugs; recover should only be used at API boundaries

  2. Initializing all pointers to empty structs 55% fail

    Hides nil-state bugs; empty struct may not be a valid state

Error Chain

Frequently confused with: