cgo and memory
- Go course
- Advanced
- Lesson 17/68
- 4 min
Learn to free memory allocated with C.CString.
cgo and memory rules
There are two memory worlds: the GC manages Go memory and you manage C memory. The core rules:
- Everything allocated in C (
C.CString,C.malloc) is released withC.free. - You may pass a Go pointer to C, but C must not keep it after the call returns.
- Go memory passed to C must not contain other Go pointers.
Freeing with defer
The easiest way to avoid leaks is to write defer C.free right below the allocation:
buf := C.malloc(1024)
defer C.free(buf)GODEBUG=cgocheck=1 (the default) checks some pointer rules at run time and panics on a violation.
Practice Allocate and free
Add #include <stdlib.h> in the preamble. Allocate memory with p := C.malloc(16), write defer C.free(p) right after it and print p != nil.
Starter code
package main
/*
// C kodu buraya
*/
import "C"
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
/*
#include <stdlib.h>
*/
import "C"
import "fmt"
func main() {
p := C.malloc(16)
defer C.free(p)
fmt.Println(p != nil)
}Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens if a C library stores a Go pointer to use later?
- There is no problem
- Go copies it automatically
- The compiler prevents it
- It breaks the rules; the GC may move or collect the memory Correct answer
Explanation: cgo pointer rules forbid C from keeping a Go pointer after the call; in such cases data is copied to C memory or runtime/cgo.Handle is used.
2 Release the memory
p := C.malloc(64)
____ C.free(p)
p := C.malloc(64)
defer C.free(p)
Explanation: defer guarantees that C.free is called when the function ends.
3 Memory and owner
| Term | Meaning |
|---|---|
make([]int, n) |
Go GC |
C.malloc(n) |
You (C.free) |
C.CString(s) |
Copies text into C memory |
cgo.Handle |
Safely passes a Go value to C |