# 错误：cgo：泄露的C内存：1024字节

- **ID:** `go/cgo-memory-leak`
- **领域:** go
- **类别:** resource_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

通过`C.malloc`分配的C内存未使用`C.free`释放，导致内存泄漏。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 1.18 | active | — | — |
| 1.19 | active | — | — |

## 解决方案

1. **Always pair `C.malloc` with `defer C.free` immediately** (95% 成功率)
   ```
   cMem := C.malloc(1024)
defer C.free(cMem)
// use cMem
   ```
2. **Use a finalizer for automatic cleanup** (80% 成功率)
   ```
   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** — Go GC only manages Go memory, not C allocations. (100% 失败率)
- **Using `defer C.free` but not in all code paths** — Early return or panic may skip defer. (60% 失败率)
