Why This Happens
The unsafe.Pointer type allows bypassing Go's type system. However, storing a uintptr (the integer form of a pointer) in a variable is dangerous because the garbage collector does not track uintptr values. The original memory may be reclaimed. Always convert in a single expression.
The Problem
func getFieldPtr(s *MyStruct) *int {
ptr := uintptr(unsafe.Pointer(s))
ptr += unsafe.Offsetof(s.Field)
// GC may move s between these lines!
return (*int)(unsafe.Pointer(ptr))
}The Fix
func getFieldPtr(s *MyStruct) *int {
return (*int)(unsafe.Pointer(
uintptr(unsafe.Pointer(s)) + unsafe.Offsetof(s.Field),
))
}Step-by-Step Fix
- 1
Identify the unsafe.Pointer usage
Find code that stores uintptr values in variables before converting back to pointers.
- 2
Combine into single expression
Perform the entire pointer arithmetic in a single expression without intermediate uintptr variables.
- 3
Consider safer alternatives
Check if reflect or encoding/binary can achieve the same goal without unsafe.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free