cgo ownership and pointer restrictions
cgo ownership and pointer restrictions
cgo connects Go to C through import "C" and the adjacent C preamble. A C allocation must be released with its matching C allocator; Go GC does not free C.CString or C.CBytes. Conversely, never pass a Go allocation to C.free. Use CGO_ENABLED=1 and a compatible C compiler. Save each program independently as main.go and run go run main.go. These examples use no external native library.
package main
/*#include <stdlib.h>#include <string.h>*/import "C"import ( "fmt" "unsafe")
func main() { p := C.CString("hello") defer C.free(unsafe.Pointer(p)) fmt.Println(C.strlen(p)) fmt.Println(C.GoString(p))}C.CString allocates and copies a NUL-terminated string; strlen stops at the first NUL. C.GoString copies back into a Go string. For binary data pass an explicit length and copy with C.GoBytes. Pair allocation and release even on error paths; do not use the C pointer after free.
Expected output:
5helloBorrow pointer-free memory for a synchronous call
package main
/*#include <stdint.h>static void bump(uint8_t *p) { (*p)++; }*/import "C"import ( "fmt" "unsafe")
func main() { data := []byte{9}; C.bump((*C.uint8_t)(unsafe.Pointer(&data[0]))); fmt.Println(data[0]) }The backing array contains no Go pointers, and C does not retain the pointer after returning. Go memory passed as a C argument is implicitly pinned for the call. Longer retention is permitted only while correctly pinned (runtime.Pinner) and subject to the full cgo pointer rules, including referenced Go memory. KeepAlive is not a pin. Do not retain Go string or slice headers in C; use C-owned copies or a handle. Never take &data[0] on an empty slice. The call is not a synchronization mechanism for concurrent writes.
Expected output:
10Try it locally
Copy the bytes {65,0,66} into C-owned memory, copy all three bytes back, free the C memory and show the result. The embedded NUL must survive.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Native interoperability 02: cgo ownership and pointer restrictions
Check the lesson objective before moving on.
Who frees memory returned by C.CString?
When may C retain a Go pointer after the call?