Staff / expert · Memory and runtime

When unsafe and cgo change the contract

Can you keep a C pointer to Go memory after a cgo call?

Try explaining this aloud before opening the answer. State your assumptions and trace a boundary case.

Reveal a strong answer
  1. Go and C have distinct lifetime and pointer rules. Whether a pointer may cross a call depends on what memory contains, how long it is retained and whether pinning is permitted and managed. Consult the current cgo rules rather than treating a pointer cast as authorization.

  2. C allocations are not reclaimed by Go GC. Allocate/free ownership must be explicit, errors must release partial resources and callbacks must obey lifetime restrictions. A Go finalizer is not a timely cleanup protocol.

  3. Prefer copying a bounded buffer or an established wrapper when possible. Account for foreign allocations in process memory and deploy the required libc/native libraries for the chosen target.

Common trap

unsafe.Pointer changes the type system view; it does not extend lifetime or legalize retained pointers.

Try it

A wrapper leaks memory but the Go heap profile stays flat. Where do you investigate?

Worked solution

Measure RSS and native allocations, audit every C allocation/free pair and error path, and check retained handles and callback lifetimes. Go heap profiles cannot attribute every byte allocated by foreign libraries.

Change the constraint

Why can enabling cgo change cross-compilation and the suitability of a scratch container?

How did you do?

Self-assessment, not a compiler pass or interview score. Explain the reasoning unaided before marking understood.

Not marked. Progress stays on this browser, separate from course completion.

Primary references

Checked 2026-10-20. Use documentation for your pinned runtime, driver and tool version.