When using cgo its my understanding that strings created with C.CString 
must be freed with C.free, but yet numeric types do not need to be 
explicitly freed.

Firstly, is CString a special case here, or are there other types that need 
to be explicitly freed as well?

Secondly, Im writing a lot of wrappers to cgo functions that will requiring 
converting go 'string' arguments in the outer function, into C.String 
arguments in the cgo inner function. Im looking for a simple way to ensure 
that I dont create any memory leaks. In view of this I have an idea to wrap 
the CString in a go struct and set the finalizer to free the CString :

// -------------------------------------- wrapped.go 

package golasso

import (
        // #include <stdlib.h>

type WrappedString struct {
        s *C.char

func FreeWrappedString(s *WrappedString) {
        fmt.Print("Freeing WrappedString")

func NewWrappedString(s string) WrappedString {
        wrappedString := WrappedString{s: C.CString(s)}
        runtime.SetFinalizer(&wrappedString, FreeWrappedString)
        return wrappedString

// --------------------------------------

func simulatedCCall(s *C.char) {

        fmt.Print("simulated C call")


// -------------------------------------- wrapped_test.go 
package golasso

import (

func TestWrapped(t *testing.T) {
        t.Logf("simulated C call")

NB: I do realise that, in a production scenario, it might be a long time 
before the GC runs and therefore a long time before the GC calls the 
finalizer to free the CString. Im not so worried about this, as my primary 
concern is ensuring that *every* CString is definitely going to be freed at 
some point, and therefore I have no *true* memory leaks.

What are the pros/cons of this? Is it even correct? Is there an easier way 
to achieve this?


You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to