为什么我的程序会泄漏内存?(在 C++ 中使用树) [英] Why is my program leaking memory? (working with trees in C++)
问题描述
我正在创建一个动态对象树.Node 类有一个向量来存储子节点,以及其他类变量:
I'm creating a tree of dynamic objects. The Node class has a vector to store the child nodes, among the other class variables:
std::vector<Node*> child;
类析构函数删除所有动态分配的类变量,然后删除子节点:
The class destructor deletes all the dynamically allocated class variables, and then deletes the child nodes:
~Node() {
//Deleting the other variables
.
.
.
//Deleting the child nodes
for(int i = 0; i < child.size(); i++) {
delete child[i];
}
}
我的类有一个方法,可以创建一棵给定高度的树,其中当前节点为根节点:
My class has a method that creates a tree of a given height, in which the current node is the root node:
void createTree(int height) {
if(height == 0) {
return;
}
for(int i = 0; i < numberOfChildNodes; i++) {
child.push_back(new Node());
child[i]->createTree(height - 1);
}
}
这个类有另一种方法,我创建一棵高度= 3的树,然后删除整棵树并创建另一棵高度= 4的树,然后删除整棵树并创建高度= 5的树,依此类推, 直到达到内存限制:
This class has another method where I create a tree with height = 3, then I delete the entire tree and create another one with height = 4, then I delete the entire tree and create one with height = 5, and so on, until a memory limit is reached:
void highestTreePossible() {
int i, height = 3;
struct sysinfo memInfo;
while(true) {
createTree(height);
sysinfo (&memInfo);
if(memInfo.freeram > limit) {
std::cout << "Highest tree possible: height = " << height;
break;
}
for(i = 0; i < child.size(); i++) {
delete child[i];
}
child.clear();
height++;
}
for(i = 0; i < child.size(); i++) {
delete child[i];
}
child.clear();
}
问题是,当我在运行highestTreePossible()方法后检查内存时,分配了大量内存,这是不应该发生的,因为我删除了所有内容.为什么我的代码会泄漏内存?
The problem is, when I check the memory after running the method highestTreePossible(), there's a lot of memory allocated, which isn't supposed to happen, because I deleted everything. Why is my code leaking memory?
推荐答案
不漏水;你没有对这种事情使用有效的测试.现代操作系统具有复杂的内存管理,您可能会观察到一个进程在任何给定时间持有"比您认为它需要的更多的内存.请放心,系统的其余部分可以在需要时使用它.
It's not leaking; you're not using a valid test for this kind of thing. Modern operating systems have complex memory management, and you may observe a process "holding on" to more memory than you think it needs at any given time. Rest assured, it is available to the rest of the system when required.
如果您担心内存问题,您需要在相当长的一段时间内观察到您的进程的消耗量持续增加,或者挂钩到您的程序本身使用的实际分配器.一个很好的方法是使用像 massif
这样的诊断工具,它与 Valgrind 一起提供(如果您使用的是兼容系统).有一些很好的可视化方法.
If you're concerned about memory, you need to observe a constant, consistent rise in consumption for your process over a significant period of time, or hook into the actual allocators used by your program itself. A great way to do this is using a diagnostic tool like massif
, which ships with Valgrind (if you're on a compatible system). There are some great ways to visualise that.
这篇关于为什么我的程序会泄漏内存?(在 C++ 中使用树)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!