Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How/when do I free the memory of a C string created by Go code?

Tags:

go

cgo

Here is my code:

helloworld.go:

package main

/*
#include <stdlib.h>
*/
import "C"

import "unsafe"

//export HelloWorld
func HelloWorld() *C.char {
    cs := C.CString("Hello World!")
    C.free(unsafe.Pointer(cs))
    return cs
}

func main() {}

node-helloworld.cc:

#include "helloworld.h"
#include <node.h>
#include <string>

namespace demo {

using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;

void Method(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();
  args.GetReturnValue().Set(String::NewFromUtf8(isolate, HelloWorld()));
}

void init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "hello", Method);
}

NODE_MODULE(helloworld, init)

}

When I execute the code I get:

�Oc

or

��#

or

���

etc

It's actually random. I seem to be getting something different every time.

It might be that I am passing char array from HelloWorld() method.

What am I missing?

UPDATE

When I remove:

C.free(unsafe.Pointer(cs))

I get the good string. And not random characters.

But I need C.free to free the memory. It is recommended here: https://blog.golang.org/c-go-cgo

The call to C.CString returns a pointer to the start of the char array, so before the function exits we convert it to an unsafe.Pointer and release the memory allocation with C.free.

I am unsure how to do this.

like image 694
jnbdz Avatar asked Dec 06 '25 07:12

jnbdz


1 Answers

The linked example frees the allocated memory because no other code needs it.

If your Go function needs to return some allocated memory so that it can be used by some C code then the Go function should not call C.free, instead the C code that uses that memory should be responsible for freeing it after it does not need it anymore.

Arbitrary example:

cgo/test/issue20910.go

cgo/test/issue20910.c

like image 137
mkopriva Avatar answered Dec 08 '25 00:12

mkopriva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!