Search code examples
gocgo

How to free C variables used in parameters


https://golang.org/cmd/cgo/ says:

// The C string is allocated in the C heap using malloc.
// It is the caller's responsibility to arrange for it to be
// freed, such as by calling C.free (be sure to include stdlib.h
// if C.free is needed).

What if I use C.CString inline as parameter? I would have to free() it anyways, right? What is best practise in this case?

Example:

ret := C.RandomCFunction(C.CString("foo"))

Solution

  • If you use it as inline parameter, you can only free it inside the function. While you could do that, it's a really bad practice. If you use this function elsewhere with a variable that you plan on using later, it will free the variable unintentionally.

    Just move the string in front of the function call as a variable, call the function and then free it.