go
runtime_error
ai_generated
true
恐慌:运行时错误:无效的内存地址或空指针解引用 [信号SIGSEGV]
panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV]
ID: go/grpc-protobuf-oneof-nil-pointer
80%修复率
86%置信度
0证据数
2024-07-12首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.0 | active | — | — | — |
| 1.1 | active | — | — | — |
根因分析
访问protobuf oneof字段而未检查是否已设置,导致空指针解引用。
English
Accessing a protobuf oneof field without checking if it is set, leading to nil pointer dereference.
解决方案
-
98% 成功率 Check if oneof field is non-nil before type assertion.
if v := msg.GetPayload(); v != nil { switch x := v.(type) { case *pb.Payload_Text: fmt.Println(x.Text) } } -
85% 成功率 Use proto.GetField to safely retrieve oneof values.
import "google.golang.org/protobuf/proto" field := proto.GetField(msg, "payload")
无效尝试
常见但无效的做法:
-
Use a type switch without nil check.
95% 失败
Oneof interface can be nil; type switch panics.
-
Assume the oneof is always populated.
90% 失败
Unmarshal may leave it nil if field is absent.