go
resource_error
ai_generated
true
错误:cgo:泄露的C内存:1024字节
error: cgo: leaked C memory: 1024 bytes
ID: go/cgo-memory-leak
80%修复率
88%置信度
0证据数
2024-06-01首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.18 | active | — | — | — |
| 1.19 | active | — | — | — |
根因分析
通过`C.malloc`分配的C内存未使用`C.free`释放,导致内存泄漏。
English
C memory allocated via `C.malloc` not freed with `C.free`, leading to memory leak.
解决方案
-
95% 成功率 Always pair `C.malloc` with `defer C.free` immediately
cMem := C.malloc(1024) defer C.free(cMem) // use cMem
-
80% 成功率 Use a finalizer for automatic cleanup
type cBuffer struct { ptr unsafe.Pointer } func newCBuffer(size int) *cBuffer { b := &cBuffer{C.malloc(C.size_t(size))} runtime.SetFinalizer(b, func(b *cBuffer) { C.free(b.ptr) }) return b }
无效尝试
常见但无效的做法:
-
Assuming Go GC will collect C memory
100% 失败
Go GC only manages Go memory, not C allocations.
-
Using `defer C.free` but not in all code paths
60% 失败
Early return or panic may skip defer.