go runtime_error ai_generated true

panic: runtime error: invalid memory address or nil pointer dereference (in goroutine)

ID: go/nil-pointer-dereference-goroutine

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-06-18First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0+ active

Root Cause

A goroutine attempted to dereference a nil pointer. This often occurs when a shared pointer is set to nil by another goroutine, or when a struct field is not initialized before being used in a goroutine.

generic

中文

某个 goroutine 尝试解引用空指针。通常发生在共享指针被另一个 goroutine 设置为 nil,或结构体字段在 goroutine 中使用前未初始化。

Workarounds

  1. 95% success
    var mu sync.Mutex
    mu.Lock()
    if ptr != nil {
        // use ptr
    }
    mu.Unlock()
  2. 90% success
    go func(v MyStruct) {
        // use v
    }(*ptr)

Dead Ends

Common approaches that don't work:

  1. 85% fail

    The pointer may become nil between the check and the dereference due to a race condition. Nil checks are not atomic with the dereference.

  2. 90% fail

    Recovering prevents the crash but leaves the program in an inconsistent state; the root cause remains.