go runtime_error ai_generated true

panic: runtime error: invalid memory address or nil pointer dereference

ID: go/goroutine-nil-pointer-nil-channel

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-07-03First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0+ active — — —

Root Cause

A goroutine dereferenced a nil pointer, often because a struct or channel field was not initialized before the goroutine started, or a nil channel was used in select.

generic

中文

某个 goroutine 解引用了空指针,通常是因为在 goroutine 启动前结构体或 channel 字段未初始化,或在 select 中使用了 nil channel。

Workarounds

  1. 90% success
    s := &Service{ch: make(chan int, 1)}
    go s.run()
  2. 85% success
    if s == nil || s.ch == nil {
    	return
    }
    // safe to use s.ch

Dead Ends

Common approaches that don't work:

  1. 75% fail

    The nil dereference indicates a real bug; recovering leaves the program in an inconsistent state and the nil access may recur.

  2. 70% fail

    Race conditions and ordering issues mean the pointer may still be nil when accessed; proper initialization must happen before goroutine launch.