英文:
Garbage collection in cgo
问题
我在Go中有以下使用cgo的代码:
func foo() {
bar := new(C.struct_bar)
...
}
在函数执行完毕后,bar会被垃圾回收吗?还是我需要显式调用free函数来释放它?
英文:
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?
答案1
得分: 5
是的,尽管struct_bar
是一个C类型,但内存是由Go分配的,并且将由Go进行回收。
然而,由C分配的内存不会被Go的垃圾回收器(GC)跟踪。C代码应该自行管理这一点,但在像C.CString
这样的情况下,由于Go触发了分配,你必须使用C.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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论