Uintptr To Unsafe Pointer

ID

go.uintptr_to_unsafe_pointer

Severity

high

Remediation Complexity

medium

Remediation Risk

medium

Remediation Effort

medium

Resource

Reliability

Language

Go

Tags

reliability, suspicious

Description

Reports a conversion of a uintptr value to unsafe.Pointerunsafe.Pointer(u) where u is a uintptr. A uintptr is a plain integer that the garbage collector does not treat as a live reference, so the memory it addressed may have moved or been freed before it is turned back into a pointer.

Rationale

Only the conversion patterns documented in the unsafe package are valid, and they all keep the uintptr inside a single expression so the referenced object stays live. Once the value is stored in a variable, the runtime is free to move or collect the object, and reconstructing a pointer from it yields a dangling reference and memory corruption. The check is conservative: it flags only an unsafe.Pointer(x) conversion whose argument resolves to uintptr, never a conversion of a real pointer.

var u uintptr = uintptr(p)
q := unsafe.Pointer(u)  // FLAW — uintptr converted back to a pointer

r := unsafe.Pointer(&n) // OK — converting a real pointer

Remediation

Keep the uintptr arithmetic and the conversion back to unsafe.Pointer within one expression, following the patterns in the unsafe package documentation, so the referenced object cannot be moved or collected in between.