Join our Newsletter — 33% off our NHI Course
Home› Guides› Go unsafe and cgo Guide: Where Go Loses…
Guide Application Security

Go unsafe and cgo Guide: Where Go Loses Its Memory Safety

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 27 November 2026 15 min read
On this page

Go is memory safe only until code imports unsafe, calls C through cgo or races on shared data, and those three places are where Go services can still suffer memory corruption. The Go specification and runtime give strong guarantees for ordinary code: bounds checks, garbage collection and no pointer arithmetic. This guide sets out those rules as the Go documentation states them, the tools that catch violations, and how to find, review and contain the code that steps outside the safe subset. It is written for Go developers, secure code reviewers and AppSec teams who own Go services. For general Go pitfalls such as injection, timeouts and path handling, see the Go Secure Coding Guide.

Key takeaways

  • Three gaps, not one. unsafe, cgo and data races are the three ways a Go program can corrupt memory, and each needs its own review rule and tool.
  • unsafe.Pointer has six valid patterns. The unsafe package documentation lists them; anything else is invalid even if it compiles and passes tests, and silence from go vet is not proof of validity.
  • cgo moves the trust boundary into C. Every linked C library brings its own memory bugs, and Go pointers handed to C must follow the pinning rules or the garbage collector can move or free memory under C's feet.
  • Racy multiword values can corrupt memory. The Go memory model warns that races on slices, strings, interfaces and maps can lead to arbitrary memory corruption, so the race detector is a safety tool, not just a correctness tool.
  • Contain, then measure. Keep unsafe and cgo code in small, owned packages, build pure Go with CGO_ENABLED=0 where possible, and track the number of packages that opt out of safety.

Go's memory safety model

In ordinary Go, index expressions on slices, arrays and strings are bounds checked at run time and panic rather than read or write out of range. Memory is reclaimed by a garbage collector, so a pointer cannot outlive the object it points to, and pointer arithmetic is not part of the language. Together these remove the out-of-bounds writes and use-after-free bugs that dominate C and C++ advisories (see the Memory-Safe Languages Guide).

The guarantees hold only while the program stays within the safe subset. The table shows where it leaves that subset and what replaces the language guarantee.

Escape hatchWhat the developer takes overTypical bug when it goes wrong
unsafe.Pointer, unsafe.Add, unsafe.Slice, unsafe.StringType layout, object bounds, keeping objects alive for the garbage collectorOut-of-bounds read or write, dangling pointer after the GC frees or moves an object, mutation of an immutable string
cgo (import "C")All memory safety inside the C code, plus correct pointer passing between Go and CBuffer overflow or use-after-free in the C library, leaks of C.CString allocations, C retaining an unpinned Go pointer
Data races on shared variablesSynchronisation of every concurrent accessTorn slice or interface values, which the memory model says can lead to arbitrary memory corruption
Assembly (.s files) and //go:linknameCalling conventions and runtime internalsStack or register corruption, breakage on Go upgrades

The unsafe package

The unsafe package documentation defines exactly which uses of unsafe.Pointer are valid. Code that does not follow one of these patterns is invalid today or may become invalid in a future Go release, even if it works now.

Valid pattern (per the unsafe docs)The rule that keeps it validWhat reviewers look for
1. Convert *T1 to Pointer to *T2T2 is no larger than T1 and the two share an equivalent memory layoutStruct casts between types that could drift apart; casts to a larger type
2. Convert Pointer to uintptr (not back)A uintptr is an integer: the GC does not update it if the object moves, and does not keep the object aliveA uintptr stored in a variable or struct field and later turned back into a pointer
3. Pointer arithmetic via uintptrDone in one expression, and the result must still point into the original allocated object; pointing past the end is invalidOffset arithmetic split across statements; offsets taken from input without bounds checks
4. Conversion in a syscall.Syscall argument listThe conversion must appear in the call expression itselfThe uintptr computed on an earlier line
5. Result of reflect.Value.Pointer or UnsafeAddrConverted to Pointer immediately, in the same expressionThe result saved to a variable first
6. reflect.SliceHeader or StringHeader Data fieldOnly when the header refers to a real slice or string; declaring one as a plain struct is invalidHeaders built from scratch; new code should use unsafe.Slice and unsafe.String instead

The newer helper functions

  • unsafe.Add and unsafe.Slice (Go 1.17): Add is defined as Pointer(uintptr(ptr) + uintptr(len)) and the usual pointer rules still apply. Slice panics on a negative length or a nil pointer with non-zero length, but it cannot check that the length matches the real allocation.
  • unsafe.String, StringData and SliceData (Go 1.20): the bytes behind a string built with unsafe.String must not be modified while the string exists, and the bytes returned by StringData must never be modified. A reused buffer behind a zero-copy conversion silently changes strings other code treats as immutable.

Review rule: every call to these helpers needs a comment stating where the length comes from and who owns the underlying memory. A length derived from untrusted input is an out-of-bounds read waiting to happen.

cgo and calling C

cgo lets Go call C and C call Go. From a safety view the important point is simple: the C side has none of Go's protections, so a C library linked through cgo carries all of its memory bugs into the Go binary, and the Go dependency scanner sees only the Go wrapper.

Pointer passing rules

The cgo command documentation sets the rules. Whether a pointer is a Go pointer depends on how the memory was allocated, not on its type.

  • Pinned memory only: all Go pointers passed to C must point to pinned Go memory. Pointers passed as call arguments are pinned for the duration of the call.
  • No nested unpinned pointers: a Go pointer may be passed only if the memory it points to does not contain Go pointers to unpinned memory.
  • C must not keep copies past pinning: C may keep a copy of a Go pointer only while the memory is pinned. Strings, slices and channels cannot be pinned, so C cannot keep copies of them.
  • runtime.Pinner for longer lifetimes: memory pinned with runtime.Pinner must be unpinned exactly as many times as it was pinned.
  • C memory is invisible to the GC: allocations made in C, including C.CString results, are not known to Go's memory manager and must be released with C.free, ideally with a defer straight after allocation.

Runtime checks and build controls

ControlEffect (per Go docs)Use it for
GODEBUG=cgocheck=1Default: fairly cheap run-time checks of the pointer passing rulesLeave on in production; never ship cgocheck=0
GOEXPERIMENT=cgocheck2Complete checking, enabled at build time, with some run-time costTest and CI builds of cgo packages
CGO_ENABLED=0Disables cgo; files that import "C" are not builtPure Go release builds and a guard that no cgo slipped in
#cgo flag allowlist, CGO_CFLAGS_ALLOW / CGO_CFLAGS_DISALLOWOnly a limited set of flags from #cgo directives is allowed by default; flags from environment variables are not subject to those limitsKeep the default allowlist; treat changes to CGO_*FLAGS in build scripts as security-relevant
go build -asan / -msanInteroperation with AddressSanitizer or MemorySanitizer on supported Linux and FreeBSD targets with a supported Clang or GCCCatching memory errors on the C side during tests and fuzzing

cgo is enabled by default for native builds where a C compiler is found, and disabled by default when cross-compiling or when no C compiler is on PATH. That means the same source can produce a cgo binary on a developer laptop and a pure Go binary in a cross-compiling pipeline. Set CGO_ENABLED explicitly in every build so the result does not depend on the build host.

Forbidding cgo with build constraints

The go tool sets the cgo build constraint when cgo is enabled, and importing "C" implies it. Two practical patterns follow. To guarantee a pure Go release, build with CGO_ENABLED=0: any package that needs cgo then fails to build or falls back to its pure Go files. To keep an optional cgo fast path, put it behind //go:build cgo and provide a pure Go file behind //go:build !cgo, so the safe implementation is always available and tested.

Data races as a safety gap

Go does not prevent data races. The Go memory model states that reads of values larger than a machine word may be implemented as several word-sized operations, so a race on a slice, string, interface or map can produce a value that never existed. Because those values carry internal (pointer, length) or (pointer, type) pairs, the memory model says such races can lead to arbitrary memory corruption.

  • Synchronise multiword state: protect shared maps, slices, interfaces and strings with sync.Mutex, channels or sync/atomic types such as atomic.Pointer[T]. The memory model's own advice is "don't be clever".
  • Run the race detector: go test -race ./.... It finds only races on paths that actually execute, so pair it with good coverage and run a -race build under realistic load in a test environment.
  • Budget for overhead: the race detector documentation gives typical memory increases of 5-10x and execution time of 2-20x, which is why it belongs in CI and staging, not production. It requires cgo and, outside macOS, a C compiler, so CI images for race builds need one even when release builds use CGO_ENABLED=0.
  • Fail the build: a race report exits with status 66 by default (GORACE option exitcode), so CI fails without extra scripting.

For race-driven logic flaws such as time-of-check to time-of-use, see the Race Condition Vulnerabilities Guide.

Finding and reviewing unsafe code

Risk areaToolWhat it catchesLimits
Invalid uintptr to unsafe.Pointer conversionsgo vet analyser unsafeptrConversions that do not match the valid patternsStatic and partial: the unsafe docs say silence is not a guarantee
unsafe.Pointer misuse at run time-gcflags=all=-d=checkptr; the Go 1.14 release notes, which introduced it, enabled it by default with -race or -msan (except on Windows at that release)Misaligned conversions to *T; arithmetic that leaves the original heap objectOnly executed paths
cgo pointer passinggo vet analyser cgocall; cgocheck at run time; GOEXPERIMENT=cgocheck2Some violations statically, more at run timeStatic check detects only some violations
Memory bugs in linked C codego build -asan or -msan with native fuzzing (go test -fuzz)Overflows, use-after-free and uninitialised reads in C called from GoLinux and FreeBSD targets with a supported C compiler
Data races-race; go vet analysers copylocks and atomicRaces at run time; locks copied by value; common sync/atomic mistakesRun-time detector needs coverage and has high overhead
Known vulnerabilities in dependenciesgovulncheckReachable vulnerable symbols in Go modules and the standard libraryDoes not see vulnerabilities in C libraries linked through cgo
Inventory of opt-outsgo list with the CgoFiles and Imports fields; a linter rule that flags imports of unsafeWhich packages, including dependencies, use cgo or unsafeShows presence, not correctness

Review questions for unsafe and cgo changes

  1. Which of the six valid unsafe.Pointer patterns does this code follow, and is it stated in a comment?
  2. Where do lengths and offsets come from, and could any of them be influenced by input?
  3. Who owns the memory, who frees it, and could the Go side drop its last reference while C or a uintptr still uses it?
  4. Does C keep any Go pointer after the call returns, and if so is the memory pinned and later unpinned exactly once per pin?

For the wider review process, see the Secure Code Review Guide; for dependency scanning, see the Go Vulnerability Management Guide.

Containment patterns

  • Quarantine packages: keep all unsafe and cgo code in one or a few internal packages (for example internal/cbridge) with a narrow, safe Go API.
  • Ownership rules in code: require CODEOWNERS approval from a named reviewer for those packages, and fail CI if a new package outside the allowlist imports unsafe or "C".
  • Copy at the boundary: prefer C.GoBytes and C.GoString copies over long-lived shared buffers. Copying removes a whole class of lifetime bugs.
  • Validate before C sees it: check lengths, encodings and ranges in Go before calling into C, so the C parser only ever sees input that passed Go-side validation.
  • Prefer pure Go: where a maintained pure Go library exists for the same job (compression, image decoding, crypto in the standard library), use it and build with CGO_ENABLED=0. This also removes the C library from the patching load.
  • Isolate what must stay in C: if a risky C parser cannot be replaced, consider running it in a separate low-privilege process or sandbox so a memory bug does not reach the main service's credentials and data.

Phased rollout for an existing codebase

  1. Inventory (week 1): list every package, first-party and dependency, that uses unsafe, cgo or assembly, and record the C libraries linked.
  2. Turn on cheap checks (week 2): make go vet ./... a blocking CI step with default analysers, and add go test -race ./... as a separate job. Start the race job as non-blocking for one sprint to clear existing findings, then make it blocking.
  3. Deep checks for opt-out packages (weeks 3 to 6): add fuzz targets for every function that crosses into C, run them under -asan, and build those packages' tests with GOEXPERIMENT=cgocheck2.
  4. Contain: move scattered unsafe code into quarantine packages and add the CI import guard.
  5. Remove: replace cgo dependencies with pure Go alternatives where possible and switch release builds to CGO_ENABLED=0. Roll back a removal by restoring the previous module version and build flags if performance or behaviour regresses in a canary.

Measuring progress

  • Number of packages importing unsafe or "C", first-party and in dependencies, tracked per release.
  • Share of release binaries built with CGO_ENABLED=0.
  • Race detector findings per month in CI, and time to fix.
  • Fuzz coverage and hours run for each cgo boundary function.
  • Open advisories in linked C libraries, which govulncheck will not show.

Framework mapping

FrameworkReferenceHow this guide applies
NIST CSF 2.0PR.PS-06 Secure software development practicesBlocking vet, race and fuzz checks in CI for Go code
NIST SP 800-53 Rev 5SA-11 Developer Testing and EvaluationRace detector, sanitiser builds and fuzzing of cgo boundaries
NIST SP 800-53 Rev 5SA-15 Development Process, Standards, and ToolsCoding rules for unsafe and cgo, CODEOWNERS and import guards
NIST SP 800-53 Rev 5SI-16 Memory ProtectionKeeping code inside Go's bounds-checked, garbage-collected subset
NIST SP 800-53 Rev 5SA-8 Security and Privacy Engineering PrinciplesQuarantine packages and process isolation for C parsers

Common failure patterns

  • Zero-copy string conversion of a reused buffer: unsafe.String over a buffer that is later overwritten, silently changing cached strings and map keys.
  • uintptr held across a statement: an address saved to a variable, then turned back into a pointer after the GC has moved or freed the object.
  • Unsized unsafe.Slice: a length taken from a header field in untrusted input, giving an out-of-bounds read.
  • Assuming govulncheck covers cgo: a C library linked through cgo with a known flaw, invisible to Go tooling because it is not a Go module.

Practitioner checklist

  • Inventory every first-party and dependency package that imports unsafe, "C" or contains assembly.
  • Make go vet ./... blocking in CI, including the unsafeptr, cgocall, copylocks and atomic analysers.
  • Run go test -race ./... in CI with a C compiler in the image, and fail on any report.
  • Check each unsafe.Pointer use against the six valid patterns and require a comment naming the pattern.
  • Test cgo packages with GOEXPERIMENT=cgocheck2, fuzzing and -asan; never set cgocheck=0 in production.
  • Set CGO_ENABLED explicitly in every build, and use 0 for release builds that do not need C.
  • Quarantine unsafe and cgo code in owned internal packages with an import guard in CI.
  • Track linked C libraries in the SBOM and follow their advisories separately from govulncheck.

Standards and references

Related NHI Mgmt Group resources: Go Secure Coding Guide · Memory-Safe Languages Guide · Go Vulnerability Management Guide · Fuzzing Guide · Secure Code Review Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.