I have the following code in Go which uses cgo:
func foo() {
bar := new(C.struct_bar)
...
}
Will bar be garbage collected after the function finishes its execution or I need to explicitly call free?
Yes, even though the struct_bar
is a C type, the memory is allocated by Go, and will be collected by Go.
Any memory allocated in C however is not tracked by the Go GC. The C code should manage this on it's own, but in cases like C.CString
where Go triggers the allocation, you must manually free the memory with C.free
.