-
Notifications
You must be signed in to change notification settings - Fork 17.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
cmd/cgo: document that C.CString should be matched with C.free #18457
Comments
I don't think this passes the three requirements for cmd/vet (see
cmd/vet/README).
You will need to demonstrate at least this error's frequency and that
people don't actually wrap a C function in cgo preamble that frees the
argument after calling the function it wraps.
Perhaps this is better addressed with better documentation. (If you think
about the issue, it's very obvious Go's GC cannot track memory returned by
C.CString as C code can retain a reference and Go can't see the reference.)
|
I was the person who came in with the issue. My initial request was actually documentation since I found the docs that said I should be running the |
Let's start with documentation and move to vet if someone can show this meets the frequency bar. |
go vet
check for calling C.CString() inline within a function call
This looks fixed. In golang.org/cmd/cgo I see:
So both the fact that the caller must Closing. |
Someone in the Go Slack channel had a memory leak in their program, that turned out to be a misunderstanding of how CStrings work. Their code did:
They expected that C.CString would be a normal GC-able object, and so lost some time tracking down the non-obvious memory leak. The cgo documentation states that
C.CString
must be accompanied by aC.free
, but if that docstring gets glossed over, the result is a hard to find bug.It would be nice if
go vet
could warn on the pattern of calling a C function with aCString
allocated inline in the function call. Such a call is most often wrong, since there's no way to free the resulting *C.char. One exception is if the C function itself frees the memory, but that is relatively unusual pattern of memory ownership in C APIs.The text was updated successfully, but these errors were encountered: