我有以下代码:
class Node {
public:
int data;
Node* parent;
std::unique_ptr<Node> left;
std::unique_ptr<Node> right;
public:
explicit Node(int d) : data(d),
parent(nullptr),
left(nullptr),
right(nullptr) { }
/*
Some functions
*/
};
class dt {
private:
Node* root;
private:
void add_helper(Node* parent, Node* node);
/*
Some helper functions
*/
public:
dt() : root(nullptr) {}
~dt() {
delete root;
}
/*
Some functions
*/
void add(int data);
};
void dt::add(int data) {
if(!root) {
root = new Node(data); // 1: memory leak
return;
}
Node* node = new Node(data); // 2: memory leak
add_helper(root, node);
}
当我扫描此代码以查找内存泄漏时 Dr. Memory 在上面注释中提到的行上显示错误。但它们真的是内存泄漏吗? dt 具有删除 root 指针的析构函数。当析构函数开始删除 root 节点时,它将递归并删除他的所有子节点。还是发生了其他事情?
最佳答案
are these lines really causing of memory leaks?
在 Node* node = new Node(data)
行分配的内存可能会泄漏。至少该示例没有显示指针将被删除的位置。所有权可能会在 add_helper
中转移,但这已被排除在示例之外。
我不熟悉 Dr. Memory,但我假设它会报告泄漏内存的分配位置;不是泄露的地方。
此外,如果您制作一个 dt
实例的拷贝,程序的行为将是未定义的,因为原始和拷贝都将尝试删除复制的指针。
要修复潜在的内存泄漏和潜在的 UB,请使用唯一指针。就像您使用 Node
一样。
I can't use unqiue_ptr for root because there are multiple pointers to the same Node.
通过在析构函数中执行 delete root;
,您的类将获得指针的唯一所有权。如果该假设是正确的,那么使用唯一指针就没有问题。如果假设不正确,那么析构函数可能会导致未定义的行为。使用它而不是唯一指针不是解决方案。您可能需要改用共享指针。
最后,除非你的树是平衡的,否则隐式递归析构函数具有线性增加的最坏情况递归深度,这很容易导致堆栈溢出。您应该平衡树(例如使用红背或 AVL 扩充)或使用迭代算法来销毁子树。
关于c++ - 内存博士 : are these lines really causing of memory leaks?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56615232/