go runtime_error ai_generated true

panic:运行时错误:无效的内存地址或空指针解引用

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

ID: go/proto-nil-pointer-deref-proto-message

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-04-18首次发现

版本兼容性

版本状态引入弃用备注
google.golang.org/protobuf 1.x active — — —

根因分析

解引用了一个 nil 的 *pb.Message,通常来自 nil 的嵌套消息字段,或与错误一起返回的 nil 响应。在 protobuf Go 中,读取 nil 消息字段返回 nil,对 nil 调用 getter 是安全的,但直接字段访问则不是。

English

A nil *pb.Message was dereferenced, typically from a nil nested message field or a nil response returned alongside an error. In protobuf Go, reading a nil message field returns nil, and calling a getter on nil is safe but direct field access is not.

generic

解决方案

  1. 92% 成功率
    Always check the error before touching the response, and use generated getters which are nil-safe:
    
    resp, err := client.GetUser(ctx, req)
    if err != nil { return err }
    name := resp.GetUser().GetName() // getters return zero values on nil
  2. 85% 成功率
    Initialize nested messages explicitly before writing to them:
    
    if resp.User == nil { resp.User = &pb.User{} }
    resp.User.Name = "alice"

无效尝试

常见但无效的做法:

  1. 80% 失败

    Recovering hides the bug and leaves the program in an inconsistent state; the nil is a logic error that must be fixed at the source.

  2. 70% 失败

    The nil is often in a nested field (e.g. resp.User.Address); checking only the outer message still panics on the inner access.