将指针移动到其他位置后删除已分配的内存

Dzu*_*yen 2 c++ algorithm memory-leaks

我正在删除二叉树的元素,它减少到以下问题:

A* a = new A(); // memory allocated to a
A* b = new A();
a = b; // now a and b points to both same memory
Run Code Online (Sandbox Code Playgroud)

我如何释放一个初始内存?

这是我在BST中删除元素val的代码.它是否有内存泄漏问题,特别是在只有一个孩子的情况下?

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;
};
Run Code Online (Sandbox Code Playgroud)

lcs*_*lcs 9

a在分配之前你必须自由b.

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
Run Code Online (Sandbox Code Playgroud)

或者,既然您正在使用C++,请使用智能指针.

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.
Run Code Online (Sandbox Code Playgroud)