i can't use defer c.free to release the cgo.cstring memory when my func return the cstring

65 views
Skip to first unread message

杜仲

unread,
Nov 17, 2020, 9:38:29 PM11/17/20
to golang-nuts
my go version is 1.13.
i used cgo.cstring in my func, and the func will return cstring.
i don't know when c complete work about the cstring memory.
if i used defer c.free to release the cstring memory, the cstring val will change and return a unexpected value, especially at often apply memory on low memory environment.
now i use a funccollect the pointer and release after 1 hour or later.
is there any other way to solve?

Ian Lance Taylor

unread,
Nov 17, 2020, 9:43:20 PM11/17/20
to 杜仲, golang-nuts
A string allocated with C.CString is allocated using the C malloc
function. It sounds like you are passing that string to C, in which
case it becomes the responsibility of the C code to free the string.
C code has to be aware of memory use and has to free memory when it is
no longer needed. If your C code does not track memory properly, that
is unfortunate, but there is nothing you can do to fix it safely on
the Go side.

Ian

杜仲

unread,
Nov 17, 2020, 10:02:48 PM11/17/20
to golang-nuts
that's the problem, i use c just like an channel, the value final send to other language. i know i can make an call back function in c and then release that memory in c code.
 regrettably, this will take many time and i don;t have so much.
however ,thx

Reply all
Reply to author
Forward
0 new messages