go runtime_error ai_generated true

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

ID: go/goroutine-panic-unhandled

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.1 active

Root Cause

A nil pointer dereference occurs inside a goroutine, causing a panic that is not recovered. This can happen when a goroutine accesses a nil pointer without checking.

generic

中文

在 goroutine 内部发生空指针解引用,导致未恢复的恐慌。当 goroutine 未经检查就访问空指针时,可能会发生这种情况。

Workarounds

  1. 90% success Add a deferred recover inside the goroutine
    go func() {
        defer func() {
            if r := recover(); r != nil {
                log.Printf("Recovered in goroutine: %v", r)
            }
        }()
        // code that may panic
        var p *int
        *p = 42 // nil pointer dereference
    }()
  2. 95% success Check for nil pointers before dereferencing
    if p != nil {
        *p = 42
    } else {
        log.Println("nil pointer")
    }

Dead Ends

Common approaches that don't work:

  1. Adding a recover in the main goroutine only 95% fail

    recover() only works within the same goroutine; panics in other goroutines cannot be recovered from the main goroutine.

  2. Ignoring the panic and hoping the program continues 99% fail

    An unhandled panic in any goroutine crashes the entire program.