go
runtime_error
ai_generated
true
panic: runtime error: invalid memory address or nil pointer dereference
ID: go/unsafe-pointer-arithmetic
80%Fix Rate
85%Confidence
0Evidence
2024-05-12First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.21 | active | — | — | — |
| 1.22 | active | — | — | — |
Root Cause
Using `unsafe.Pointer` arithmetic incorrectly, resulting in accessing out-of-bounds memory.
generic中文
错误地使用`unsafe.Pointer`算术,导致访问越界内存。
Workarounds
-
90% success 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)
-
75% success 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))
Dead Ends
Common approaches that don't work:
-
Adding offset without aligning to type size
70% fail
Unaligned access can cause crash on some architectures.
-
Using `uintptr` as pointer without pinning
80% fail
GC may move the object, making uintptr stale.