`contrib.OpenCVResult` 中 C 分配的 `OpenCVResult.Message` 可能存在内存泄漏
作者: OvOhao创建于 2026年8月28日更新于 2026年8月28日
- Go calls any wrapped contrib operation — e.g. the contrib wrappers (return OpenCVResult(C.SomeContribCall(...))).
- The C++ wrapper runs the OpenCV call inside try/catch; on cv::Exception it returns errorResult(e.code, e.what()).
- errorResult malloc s strlen(message)+1 bytes, copies the message in, and stores the pointer in the returned-by-value struct field ri.Message. cgo copies the struct into the Go frame, so result.Message becomes the only reference to that heap block in the program.
- contrib/errors.go:14 calls C.GoString(result.Message), which copies the bytes into a new Go string, then returns. There is no defer, no unsafe import, and no C.free anywhere in the file; result is a by-value parameter, so after the function returns no Go code holds the pointer and no other function is able to free it.
- One malloc block of strlen(e.what())+1 bytes is leaked per failed operation. OpenCV exception strings have the form OpenCV() :: error: (
:) in function '', typically 120–400 bytes and growing with the source path length.
内容来源: hybridgroup/gocv