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
unsafepackage documentation lists them; anything else is invalid even if it compiles and passes tests, and silence fromgo vetis 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=0where 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 hatch | What the developer takes over | Typical bug when it goes wrong |
|---|---|---|
unsafe.Pointer, unsafe.Add, unsafe.Slice, unsafe.String | Type layout, object bounds, keeping objects alive for the garbage collector | Out-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 C | Buffer overflow or use-after-free in the C library, leaks of C.CString allocations, C retaining an unpinned Go pointer |
| Data races on shared variables | Synchronisation of every concurrent access | Torn slice or interface values, which the memory model says can lead to arbitrary memory corruption |
Assembly (.s files) and //go:linkname | Calling conventions and runtime internals | Stack 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 valid | What reviewers look for |
|---|---|---|
1. Convert *T1 to Pointer to *T2 | T2 is no larger than T1 and the two share an equivalent memory layout | Struct 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 alive | A uintptr stored in a variable or struct field and later turned back into a pointer |
3. Pointer arithmetic via uintptr | Done in one expression, and the result must still point into the original allocated object; pointing past the end is invalid | Offset arithmetic split across statements; offsets taken from input without bounds checks |
4. Conversion in a syscall.Syscall argument list | The conversion must appear in the call expression itself | The uintptr computed on an earlier line |
5. Result of reflect.Value.Pointer or UnsafeAddr | Converted to Pointer immediately, in the same expression | The result saved to a variable first |
6. reflect.SliceHeader or StringHeader Data field | Only when the header refers to a real slice or string; declaring one as a plain struct is invalid | Headers 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):
Addis defined asPointer(uintptr(ptr) + uintptr(len))and the usual pointer rules still apply.Slicepanics 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.Stringmust not be modified while the string exists, and the bytes returned byStringDatamust 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.Pinnermust be unpinned exactly as many times as it was pinned. - C memory is invisible to the GC: allocations made in C, including
C.CStringresults, are not known to Go's memory manager and must be released withC.free, ideally with adeferstraight after allocation.
Runtime checks and build controls
| Control | Effect (per Go docs) | Use it for |
|---|---|---|
GODEBUG=cgocheck=1 | Default: fairly cheap run-time checks of the pointer passing rules | Leave on in production; never ship cgocheck=0 |
GOEXPERIMENT=cgocheck2 | Complete checking, enabled at build time, with some run-time cost | Test and CI builds of cgo packages |
CGO_ENABLED=0 | Disables cgo; files that import "C" are not built | Pure Go release builds and a guard that no cgo slipped in |
#cgo flag allowlist, CGO_CFLAGS_ALLOW / CGO_CFLAGS_DISALLOW | Only a limited set of flags from #cgo directives is allowed by default; flags from environment variables are not subject to those limits | Keep the default allowlist; treat changes to CGO_*FLAGS in build scripts as security-relevant |
go build -asan / -msan | Interoperation with AddressSanitizer or MemorySanitizer on supported Linux and FreeBSD targets with a supported Clang or GCC | Catching 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 orsync/atomictypes such asatomic.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-racebuild 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 (
GORACEoptionexitcode), 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 area | Tool | What it catches | Limits |
|---|---|---|---|
Invalid uintptr to unsafe.Pointer conversions | go vet analyser unsafeptr | Conversions that do not match the valid patterns | Static 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 object | Only executed paths |
| cgo pointer passing | go vet analyser cgocall; cgocheck at run time; GOEXPERIMENT=cgocheck2 | Some violations statically, more at run time | Static check detects only some violations |
| Memory bugs in linked C code | go build -asan or -msan with native fuzzing (go test -fuzz) | Overflows, use-after-free and uninitialised reads in C called from Go | Linux and FreeBSD targets with a supported C compiler |
| Data races | -race; go vet analysers copylocks and atomic | Races at run time; locks copied by value; common sync/atomic mistakes | Run-time detector needs coverage and has high overhead |
| Known vulnerabilities in dependencies | govulncheck | Reachable vulnerable symbols in Go modules and the standard library | Does not see vulnerabilities in C libraries linked through cgo |
| Inventory of opt-outs | go list with the CgoFiles and Imports fields; a linter rule that flags imports of unsafe | Which packages, including dependencies, use cgo or unsafe | Shows presence, not correctness |
Review questions for unsafe and cgo changes
- Which of the six valid
unsafe.Pointerpatterns does this code follow, and is it stated in a comment? - Where do lengths and offsets come from, and could any of them be influenced by input?
- Who owns the memory, who frees it, and could the Go side drop its last reference while C or a
uintptrstill uses it? - 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
unsafeand cgo code in one or a few internal packages (for exampleinternal/cbridge) with a narrow, safe Go API. - Ownership rules in code: require
CODEOWNERSapproval from a named reviewer for those packages, and fail CI if a new package outside the allowlist importsunsafeor "C". - Copy at the boundary: prefer
C.GoBytesandC.GoStringcopies 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
- Inventory (week 1): list every package, first-party and dependency, that uses
unsafe, cgo or assembly, and record the C libraries linked. - Turn on cheap checks (week 2): make
go vet ./...a blocking CI step with default analysers, and addgo test -race ./...as a separate job. Start the race job as non-blocking for one sprint to clear existing findings, then make it blocking. - 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 withGOEXPERIMENT=cgocheck2. - Contain: move scattered unsafe code into quarantine packages and add the CI import guard.
- 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
unsafeor "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
govulncheckwill not show.
Framework mapping
| Framework | Reference | How this guide applies |
|---|---|---|
| NIST CSF 2.0 | PR.PS-06 Secure software development practices | Blocking vet, race and fuzz checks in CI for Go code |
| NIST SP 800-53 Rev 5 | SA-11 Developer Testing and Evaluation | Race detector, sanitiser builds and fuzzing of cgo boundaries |
| NIST SP 800-53 Rev 5 | SA-15 Development Process, Standards, and Tools | Coding rules for unsafe and cgo, CODEOWNERS and import guards |
| NIST SP 800-53 Rev 5 | SI-16 Memory Protection | Keeping code inside Go's bounds-checked, garbage-collected subset |
| NIST SP 800-53 Rev 5 | SA-8 Security and Privacy Engineering Principles | Quarantine packages and process isolation for C parsers |
Common failure patterns
- Zero-copy string conversion of a reused buffer:
unsafe.Stringover 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 theunsafeptr,cgocall,copylocksandatomicanalysers. - Run
go test -race ./...in CI with a C compiler in the image, and fail on any report. - Check each
unsafe.Pointeruse against the six valid patterns and require a comment naming the pattern. - Test cgo packages with
GOEXPERIMENT=cgocheck2, fuzzing and-asan; never setcgocheck=0in production. - Set
CGO_ENABLEDexplicitly in every build, and use0for 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
- Go: Package unsafe
- Go: Command cgo
- Go: The Go Memory Model
- Go: Data Race Detector
- Go: Command vet
- Go: Go 1.14 Release Notes (checkptr)
- Go: Security Best Practices for Go Developers
- CISA and NSA: Memory Safe Languages: Reducing Vulnerabilities in Modern Software Development
Related NHI Mgmt Group resources: Go Secure Coding Guide · Memory-Safe Languages Guide · Go Vulnerability Management Guide · Fuzzing Guide · Secure Code Review Guide