【发布时间】:2016-05-08 00:32:44
【问题描述】:
所以我似乎无法找出我为什么会泄漏内存,有人可以帮忙吗?我用operator=:实现了一个二叉搜索树
BinTree& BinTree::operator=(const BinTree &other)
{
if (other.root == NULL)
root = NULL;
else
{
copyHelper(root, other.root);
}
return *this;
}
复制助手:
void BinTree::copyHelper(Node *¤t, const Node *other)
{
if (other == NULL)
current = NULL;
else
{
current = new Node;
current->data = other->data;
copyHelper(current->left, other->left);
copyHelper(current->right, other->right);
}
}
我知道current = new Node; 是发生泄漏的地方,但是如果我尝试在该行之前执行delete current;,我的程序就会崩溃。
这是我的析构函数:
BinTree::~BinTree()
{
destroyRecursive(root);
}
void BinTree::destroyRecursive(Node *node)
{
if (node)
{
destroyRecursive(node->left);
destroyRecursive(node->right);
delete node;
}
}
【问题讨论】:
-
那么你的
Node析构函数是什么样的?注意你还需要深拷贝data,不清楚这是否发生。 -
你没有显示一个
delete,那么任何人应该如何评论潜在的泄漏? -
@EJP 我添加了析构函数
-
@EJP 好的,但我仍然在泄漏内存
标签: c++ memory memory-leaks variable-assignment assignment-operator