Release go strings pointers on the C

Hi,

I don’t know go, just basic level, but I would need some help on how go interacts with C.
I have a static library written in go which exports in a C header some functions, and they are used into a C program. The functions return char* and on go are created with C.CString. The documentation says that the created objects are on C heap, and I want to release them on C code. For this I’m using free.

  1. Is this the correct way to do it(because documentation says the pointers on the C heap), or the objects must be sent back to go and release them with C.free?
  2. Can there be any problems if the pointers created on go are freed on C, e.g. if the go static library is compiled with an OS version, but the final executable with another? Meaning maybe different libc(free/malloc) versions are used.

Thank you

Hi, Marius, and welcome to the forum!

Mixing the allocation and freeing of pointers between potentially different malloc implementations can lead to problems. It has been my experience that in Go, it’s a good idea to put the allocation and (deferred) freeing in the same spot rather than allocating in one place and freeing in another:

func callCFunction(parameter string) int {
    cstr := C.CString(parameter)
    defer C.free(cstr)
    int(return C.function(cstr))
}

Hi Sean,

Thanks for info, unfortunately I have a bit different, the CString continues to live into the C world:

func goFunction() C.char* {
   return  C.CString("abc")

and then into C

void cFunction() 
{
    char* ptr = goFunction();
   // and now now to free ptr
  goDealoc(ptr); // which will do C.free() internally?
  // or
  free(ptr);
}

Thanks

Ah, OK, in that case, assuming goDealloc is implemented as something like:

func goDealloc(p unsafe.Pointer) {
    C.free(p)
}

I would recommend goDealloc because then I would expect that whatever malloc the Go compiler uses to implement C.CString would pair together with whatever Go uses for C.free.

Disclaimer (which I should have mentioned in my first response): I am not a C or Cgo (or Go, for that matter :slightly_smiling_face:) specialist, so my answers here are based on my intuition and limited knowledge of C’s separate compilation and linking steps.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.