go runtime_error ai_generated true

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

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

ID: go/unsafe-pointer-arithmetic

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

版本兼容性

版本状态引入弃用备注
1.21 active
1.22 active

根因分析

错误地使用`unsafe.Pointer`算术,导致访问越界内存。

English

Using `unsafe.Pointer` arithmetic incorrectly, resulting in accessing out-of-bounds memory.

generic

解决方案

  1. 90% 成功率 Use `unsafe.Add` for safe pointer arithmetic (Go 1.17+)
    p := unsafe.Pointer(&arr[0])
    next := unsafe.Add(p, unsafe.Sizeof(arr[0])*2)
    _ = *(*int)(next)
  2. 75% 成功率 Convert to `uintptr` only immediately before use and pin
    runtime.KeepAlive(arr)
    ptr := uintptr(unsafe.Pointer(&arr[0])) + unsafe.Sizeof(arr[0])
    _ = *(*int)(unsafe.Pointer(ptr))

无效尝试

常见但无效的做法:

  1. Adding offset without aligning to type size 70% 失败

    Unaligned access can cause crash on some architectures.

  2. Using `uintptr` as pointer without pinning 80% 失败

    GC may move the object, making uintptr stale.