我正在删除二叉树的元素,它简化为以下问题:
A* a = new A(); // memory allocated to a
A* b = new A();
a = b; // now a and b points to both same memory
如何释放a的初始内存?
这是我在 BST 中删除元素 val 的代码。是否存在内存泄漏问题,尤其是在只有一个 child 的情况下?
Node* remove_helper(Node* n , int value)
{
if (n == NULL)
return NULL;
if (value < n->value)
n->left = remove_helper(n->left, value);
else if (value > n->value)
n->right = remove_helper(n->right, value);
else {
if (n->left == NULL && n->right == NULL) {
delete n;
return NULL;
}
if (n->left == NULL) {
return n->right;
}
else if (n->right == NULL) {
return n->left;
}
else {
Node* tmp = n;
n = rightMostChild(n->left);
n->left = rightMostDelete(tmp->left);
n->right = tmp->right;
}
}
return n;
};
最佳答案
在将 b
分配给它之前,您必须先释放 a
。
A* a = new A(); // memory allocated to a
A* b = new A();
delete a;
a = b; // now a and b points to both same memory
或者,由于您使用的是 C++
,因此请使用 smart pointer .
auto a = std::make_shared<A>();
auto b = std::make_shared<A>();
a = b; // the original instance of `A` pointed to by `a` will be deleted
// when b is assigned.
关于c++ - 将指针移动到其他位置后删除分配的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29611928/