【发布时间】:2018-05-18 03:38:08
【问题描述】:
以下 Vala 代码与 C 结合导致内存泄漏,我无法理解它。
Main.vala
using GLib;
[CCode (cname = "c_function")]
public static extern void c_function (out Tree<int, Tree<int, string>> tree);
public static int main () {
Tree<int, Tree<int, string>> tree;
c_function (out tree);
// If code were to end here and return 0, no memory leak happens, but
// if we call c_function again, memory leak happens according to valgrind
c_function (out tree); // Leak happens on this second call
return 0;
}
main.c
#include <glib.h>
gint treeCompareFunction (gint a, gint b);
void extern c_function (GTree **tree) {
*tree = g_tree_new ((GCompareFunc)treeCompareFunction);
for (int i = 0; i < 3; i++) {
// Memory leak in the next line when function is called a second time
GTree * nestedTree = g_tree_new ((GCompareFunc)treeCompareFunction);
g_tree_insert (nestedTree, i, "value 1");
g_tree_insert (*tree, i, (gpointer) nestedTree);
}
}
gint treeCompareFunction (gint a, gint b) {
if (a < b) return -1;
if (a == b) return 0;
return 1;
}
我不明白为什么如果我只在没有发生内存泄漏时调用 C 函数,但如果我第二次调用它,main.c 的 line 10 > 在 for 循环中创建树会导致内存泄漏。
代码用
编译valac Main.vala main.c -g
然后运行
valgrind --leak-check=yes ./Main
我想知道是否可以解决它。在第二次调用 C 函数之前,我尝试清空 Vala 代码中的树。没有成功。如果在第二次调用 C 函数时它不是 NULL,还尝试破坏作为参数传递的树。也没有成功。仍然出现内存泄漏。
【问题讨论】:
标签: c memory-management memory-leaks valgrind vala