为什么在NULL检查后会在指针上调用递归函数?

时间:2013-03-19 22:15:03

标签: c++ pointers memory-management

// So I call this function after deleting a node.
// It works before I delete the node, but for some reason
// after I perform a deletion and update the tree it runs into
// EXC_BAD_ACCESS on the line below...

void BinaryTree::updateCost(BinaryNode *root) {
    if (root != NULL)
        root->updateCostRecursively(1);
}

void BinaryNode::updateCostRecursively(int newCost) {
    cout << this << endl; // prints 0x3000000000000000 before the bad access
    cost = newCost; // has a bad access here
    if (right != NULL)
        right->updateCostRecursively(newCost + 1);
    if (left != NULL)
        left->updateCostRecursively(newCost + 1);
}

为什么这个递归函数在NULL对象上调用,即使我每次都检查指针?

我复制了用于删除下面节点的代码。我仍然无法理解递归函数,但是从什么情况来看,我不会留下一个悬垂的指针。

BinaryNode *BinaryTree::findMin(BinaryNode *t) {
    if (t == NULL) return NULL;
    while (t->left != NULL) t = t->left;
    return t;
}

BinaryNode *BinaryTree::removeMin(BinaryNode *t) {
    if (t == NULL) return NULL;
    if (t->left != NULL)
        t->left = removeMin(t->left);
    else {
        BinaryNode *node = t;
        t = t->right;
        delete node;
    }
    return t;
}

bool BinaryTree::remove(int key) {
    if (root != NULL && remove(key, root))
        return true;
    return false;
}

BinaryNode *BinaryTree::remove(int x, BinaryNode *t) {
    if (t == NULL) return NULL;

    if (x < t->key)
        t->left = remove(x, t->left);
    else if (x > t->key)
        t->right = remove(x, t->right);
    else if (t->left != NULL && t->right != NULL) {
        // item x is found; t has two children
        t->key = findMin(t->right)->key;
        t->right = removeMin(t->right);
    } else { //t has only one child
        BinaryNode *node = t;       
        t = (t->left != NULL) ? t->left : t->right;
        delete node;
    }

    updateCost(root);
    return t;
}

1 个答案:

答案 0 :(得分:1)

错误在您的删除方法中,而不是您发布的代码。删除节点(例如root->right)后,您需要设置root->right = NULL。您使用delete所做的就是释放指针所指向的内存。指针本身继续指向该地址。你得到一个糟糕的访问异常,因为你正试图访问释放的内存。