【发布时间】:2018-05-05 22:32:06
【问题描述】:
此代码导致以下错误
free(): invalid pointer
using GLib;
using GLib.Random;
// Global variable
Tree<string, Tree<int, string> > mainTree;
public static int main (string[] args) {
// Initiate random seed
Random.set_seed ((uint32) get_monotonic_time());
// mainTree initialization
mainTree = new Tree<string, Tree<int, string> >.full (mainTreeCompareDataFunction, free, free);
// Random sized for loop
for (int i = 0; i < int_range (1000, 10001); i++) {
// If a condition is met (i is even)
if (i % 2 == 0) {
// Create a Tree to nest onto mainTree
Tree<int, string> treeToNest = new Tree<int, string>.full (treeToNestCompareDataFunction, free, free);
// Insert random content into treeToNest
treeToNest.insert (int_range (0, 101), randomString ());
// Insert the tree onto mainTree
mainTree.insert (randomString (), treeToNest);
}
}
// Empty the tree
mainTree.@foreach ((mainTreeKey, mainTreeValue) => {
mainTree.remove (mainTreeKey); // This line causes a free(): invalid pointer error
return false;
});
return 0;
}
public string randomString () {
string charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
string stringToReturn = "";
// Create a random 8 character string
for (int i = 0; i < 8; i++) {
stringToReturn += charset[int_range (0, charset.length)].to_string ();
}
return stringToReturn;
}
public int treeToNestCompareDataFunction (int a, int b) {
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
public int mainTreeCompareDataFunction (string a, string b) {
return strcmp (a, b);
}
我怀疑这是因为树中有一个嵌套的GLib.Tree,而free() 不能用于这些对象。如果我使用null 代替mainTree 的值的destroy 函数,则不会发生崩溃,但是如果我要重用mainTree 变量,则会产生内存泄漏。
有没有办法清空树并释放内存?
【问题讨论】:
标签: memory-management glib vala