2014-10-04 06:45
浏览 281


I'm confused about which variables need to be freed if I'm using C variables in Go.

For example, if I do this:

    s := C.CString(`something`)

Is that memory now allocated until I call, or is that OK to be garbage collected by Go when the function ends?

Or is it only variables that are created from the imported C code that need to be freed, and these C variables created from the Go code will be garbage collected?

图片转代码服务由CSDN问答提供 功能建议



  s:= C.CString(`something`)



  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongshao4207 2014-10-04 06:47

    The documentation does mention:

    // Go string to C string
    // The C string is allocated in the C heap using malloc.
    // It is the caller's responsibility to arrange for it to be
    // freed, such as by calling (be sure to include stdlib.h
    // if 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

    The article "C? Go? Cgo!" shows that you don't need to free C numeric types:

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

    But you would for string:

    import "C"
    import "unsafe"
    func Print(s string) {
        cs := C.CString(s)
        C.fputs(cs, (*C.FILE)(C.stdout))
    打赏 评论

相关推荐 更多相似问题