gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:42:31 25 4
gpt4 key购买 nike

// 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;
}

最佳答案

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

关于c++ - 为什么在 NULL 检查后会在指针上调用递归函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15511564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com