【发布时间】:2018-05-26 14:50:40
【问题描述】:
在 Vala 中,我有一个来自 Gee 库的 TreeMultiMap,它被创建为类的私有变量。当我使用树多映射并用数据填充它时,进程的内存消耗增加到 14.2 MiB。当我清除仍然是同一个变量的树多重映射并再次使用它,但添加较少的数据时,进程的内存消耗不会增加,但也不会减少。它保持在 14.2 MiB。
代码如下MultiMapTest.vala
using Gee;
private TreeMultiMap <string, TreeMultiMap<string, string> > rootTree;
public static int main () {
// Initialize rootTree
rootTree = new TreeMultiMap<string, TreeMultiMap<string, string> > (null, null);
// Add data repeatedly to the tree to make the process consume memory
for (int i = 0; i < 10000; i++) {
TreeMultiMap<string, string> nestedTree = new TreeMultiMap<string, string> (null, null);
nestedTree.@set ("Lorem ipsum", "Lorem ipsum");
rootTree.@set ("Lorem ipsum", nestedTree);
}
stdout.printf ("Press ENTER to clear the tree...");
// Wait for the user to press enter
var input = stdin.read_line ();
// Clear the tree
rootTree.clear ();
stdout.printf ("Press ENTER to continue and refill the tree with less data...");
// Wait for the user to press enter
input = stdin.read_line ();
// Refill the tree but with much less data
for (int i = 0; i < 10; i++) {
TreeMultiMap<string, string> nestedTree = new TreeMultiMap<string, string> (null, null);
nestedTree.@set ("Lorem ipsum", "Lorem ipsum");
rootTree.@set ("Lorem ipsum", nestedTree);
}
stdout.printf ("Press ENTER to quit...");
// Wait for the user to press enter
input = stdin.read_line ();
return 0;
}
用valac --pkg gee-0.8 -g MultiMapTest.vala编译
这是否被视为内存泄漏?如果是这样,是否有任何方法可以正确处理这种情况,例如一旦清除树多映射,即使涉及使用其他数据结构,内存也会释放给操作系统?
我使用了 valgrind,但无法检测到任何内存泄漏。我的看法是,一旦为TreeMultiMap 变量分配了内存,除非变量超出范围,否则程序将保持分配的内存直到其生命周期结束,而不是将其释放回操作系统。即使 TreeMultiMap 被清空。
【问题讨论】: