Freeing C Variables in Golang?

I am confused as to what variables need to be freed if I use C variables in Go.

For example, if I do this:

    s := C.CString(`something`)

      

Is this memory allocated until I call C.free(unsafe.Pointer(s))

, or is it OK to be garbage collected by Go when the function ends?

Or is it just variables created from imported C code that needs to be freed, and those C variables created from Go code will be garbage collected?

+3


source to share


1 answer


The documentation mentions :

// Go string to C string
// The C string is allocated in the C heap using malloc.
// It is the caller 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).
func C.CString(string) *C.char

      

The wiki shows an example :

package cgoexample

/*
#include <stdio.h>
#include <stdlib.h>

void myprint(char* s) {
        printf("%s", s);
}
*/
import "C"

import "unsafe"

func Example() {
        cs := C.CString("Hello from stdio\n")
        C.myprint(cs)
        C.free(unsafe.Pointer(cs))
}

      




Article " " C? Go? Cgo! "shows that you don't need to deallocate C numeric types:

func Random() int {
    var r C.long = C.random()
    return int(r)
}

      

But you would point to the line:

import "C"
import "unsafe"

func Print(s string) {
    cs := C.CString(s)
    C.fputs(cs, (*C.FILE)(C.stdout))
    C.free(unsafe.Pointer(cs))
}

      

+5


source







All Articles