go
resource_error
ai_generated
true
error: cgo: leaked C memory: 1024 bytes
ID: go/cgo-memory-leak
80%Fix Rate
88%Confidence
0Evidence
2024-06-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.18 | active | — | — | — |
| 1.19 | active | — | — | — |
Root Cause
C memory allocated via `C.malloc` not freed with `C.free`, leading to memory leak.
generic中文
通过`C.malloc`分配的C内存未使用`C.free`释放,导致内存泄漏。
Workarounds
-
95% success Always pair `C.malloc` with `defer C.free` immediately
cMem := C.malloc(1024) defer C.free(cMem) // use cMem
-
80% success 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 }
Dead Ends
Common approaches that don't work:
-
Assuming Go GC will collect C memory
100% fail
Go GC only manages Go memory, not C allocations.
-
Using `defer C.free` but not in all code paths
60% fail
Early return or panic may skip defer.