The cgo pointer-check trap: why moving an argument to a variable can panic your Go programNote · digest for December 5
Surrealist still life of the cgo pointer trap: a fragile glass bridge between two memory platforms where moving one pin triggers a red alarm
Note3 sections≈ 5 min

The cgo pointer-check trap: why moving an argument to a variable can panic your Go program

Imagine a routine code review. A function has a long C library call like C.process(unsafe.Pointer(&ctx.header), C.size_t(n)). To make it easier to read, you pull hdrPtr := unsafe.Pointer(&ctx.header) onto the line above. In pure Go, that refactor changes nothing.

When cgo (Go's built-in bridge for calling C functions) is involved, moving that argument into a variable can crash valid code with a panic. Even if it doesn't panic, a hot call can quietly become hundreds of times slower.

Same pointer: works inline, panics through a variable

Take a struct with a plain integer and a pointer to Go memory. Under cgo rules, passing the address of s.small to C is completely legal: the docs state that only the memory of that field is checked, not the whole struct.

/*
void take_ptr(void *p) {}
*/
import "C"
import "unsafe"

type S struct {
    small int32 // plain integer, no pointers
    ptr   *int  // unpinned Go pointer
}

func demo() {
    x := 42
    s := &S{small: 7, ptr: &x}

    // Works: field address is inline in the call
    C.take_ptr(unsafe.Pointer(&s.small))

    // Panics: same address, but stored in a variable
    p := unsafe.Pointer(&s.small)
    C.take_ptr(p)
}

The first call passes cleanly. The second crashes with runtime error: argument of cgo function has Go pointer to unpinned Go pointer. Both pass the exact same memory address, yet the runtime reacts in opposite ways.

The nasty part is that tests with stack-allocated or empty structs won't catch this. The panic only hits in production once s escapes to the heap and a neighboring field holds a non-nil pointer or slice.

Why it happens: syntax rewriting and two runtime paths

Go's garbage collector (GC) tracks every reference to Go objects. C code knows nothing about Go's GC, so cgo forbids passing memory that contains unpinned Go pointers.

To enforce this at runtime, cmd/cgo wraps every C.func(...) call at build time and inserts a _cgoCheckPointer check. The catch is that the preprocessor rewrites the syntax tree (AST) before type checking.

In src/cmd/cgo/gcc.go, rewriteCall recognizes three patterns: &x (checkAddr), &a[i] (checkIndex), and x[i:j] (checkSlice). If the argument matches, cgo keeps its Go type. If it sees a variable p, none of the patterns match, so it falls back to a generic path.

// Case 1: C.take_ptr(unsafe.Pointer(&s.small))
func() {
    _cgoBase0 := &s.small // *int32 type is preserved
    _cgo0 := unsafe.Pointer(_cgoBase0)
    _cgoCheckPointer(_cgoBase0, 0 == 0) // fast field check
    C.take_ptr(_cgo0)
}()

// Case 2: p := unsafe.Pointer(&s.small); C.take_ptr(p)
func() {
    _cgo0 := p
    _cgoCheckPointer(_cgo0, nil) // scans whole heap struct
    C.take_ptr(_cgo0)
}()

In src/runtime/cgocall.go, the two paths split. In case 1, cgoCheckPointer receives *int32, sees there are no pointers inside that field, and returns at once. It never touches neighboring fields.

In case 2, the runtime calls cgoCheckUnknownPointer. It uses findObject to locate the start of the whole heap allocation and scans every pointer in the object. It hits s.ptr and panics right away.

Even when neighboring fields are nil, the full scan still runs. Measurements by Shraddha Agrawal show the slow path takes 110–1,600x longer, jumping from tens of nanoseconds to tens of microseconds. You'll spot runtime.cgoCheckUnknownPointer and runtime.findObject in CPU profiles, and global variables in data/bss always panic.

How to write cgo calls without panics or slowdowns

Using a typed variable like p := &s.small with C.take_ptr(unsafe.Pointer(p)) won't save you. cmd/cgo strips the unsafe.Pointer(...) wrapper, sees p instead of &, and still passes nil.

To avoid this trap:

  1. Keep &x, &a[i], and a[:] directly inside the C.func(...) call (wrapping them inline with unsafe.Pointer(&s.small) is fine).
  2. If C code needs nested Go pointers or keeps memory after returning, pin objects with runtime.Pinner from Go 1.21+.
// Option 1: field address inline in the call
C.take_ptr(unsafe.Pointer(&s.small))

// Option 2: explicit GC pinning
var pinner runtime.Pinner
pinner.Pin(s.ptr)
defer pinner.Unpin()
p := unsafe.Pointer(&s.small)
C.take_ptr(p)

After pinner.Pin(s.ptr), the garbage collector leaves the object alone until Unpin, so passing through a variable works without a panic.

Turning off checks in production with GODEBUG=cgocheck=0 is risky because it removes your safety net against silent memory corruption. In tests, do the opposite: enable strict checks with GOEXPERIMENT=cgocheck2.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 6