这个 Vala 代码在构建为共享库 (.so) 时会发生内存泄漏吗?
瓦拉:
namespace test {
public static string info(string name){
return "Hello " + name;
}
}
源代码(valac -C
)
gchar* test_info (const gchar* name) {
gchar* result = NULL;
const gchar* _tmp0_ = NULL;
gchar* _tmp1_ = NULL;
g_return_val_if_fail (name != NULL, NULL);
_tmp0_ = name;
_tmp1_ = g_strconcat ("Hello ", _tmp0_, NULL);
result = _tmp1_;
return result;
}
编译:valac --library=test -H test.h "test.vala"-X -fPIC -X -shared -o test.so
令我惊讶的是 test_info
中没有内存释放。
g_strconcat
会将分配的内存存储在全局变量中(可能是线程局部变量)吗?- 如果我从外部程序调用
test_info
多次而不释放内存,会发生内存泄漏吗?
我对这个可能的简单问题感到抱歉,但我是 Vala 的新手(我在 Go、Python、C++ 等领域的主要经验)
最佳答案
您的代码将返回一个拥有字符串,因此调用者负责内存释放。
如果您从 vala 调用此库函数,编译器将确保它已被释放。
如果您从 C
调用它,您应该阅读 GLib documentation for g_strconcat :
Concatenates all of the given strings into one long string. The returned string should be freed with g_free() when no longer needed.
我建议您阅读:
另请参阅this question (虽然这是关于 Sprite ,瓦拉斯“姐妹语言”)。
关于c - Vala构建共享库时是否存在内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31406075/