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

谁都会走 提交于 2019-12-11 05:06:03

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/47194827/how-when-do-i-free-the-memory-of-a-c-string-created-by-go-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!