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

时间:2015-04-13 17:58:17

标签: 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

如何释放?

的初始记忆

这是我在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;
};

1 个答案:

答案 0 :(得分: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

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. ,请使用smart pointer

{{1}}