gpt4 book ai didi

c++ - 当我尝试删除不存在的值时,为什么删除操作会出现段错误?

转载 作者:太空宇宙 更新时间:2023-11-04 13:00:41 25 4
gpt4 key购买 nike

这是我为不同的家庭作业编写的帮助程序。 - 完全披露 - 我不必提交此代码,但我正在使用有效的 BST 实现来验证我的作业的顺序遍历、预排序遍历和后序遍历。遍历工作正常,但是当我在传递的值不存在时调用 remove(int) 时,我得到了一个完全不相关的错误。当存在传递值时,一切正常。我的删除操作由三个辅助函数组成:remove、deleteNode 和 makeDeletion。我想让这个 bst 类功能齐全。谢谢。

    // remove(int) is a private function called from main
// when num exists in the BST there are no errors
// when num does not exist in BST there is a seg fault

void IntBST::remove(int num)
{ deleteNode(num, root); }

// deleteNode is a private function
// that searches for the node containing num

void IntBST::deleteNode(int num, Node *&p)
{
if (num < p->val)
deleteNode(num, p->left);
else if (num > p->val)
deleteNode(num, p->right);
else
makeDeletion(p);
}

// makeDeletion resets the bst after deleting the passed node

void IntBST::makeDeletion(Node *&p)
{
Node *temp = NULL;

if (!p)
cout << "\n Cannot delete empty node." << endl;

// for nodes with one child
else if (!p->right)
{
temp = p;
p = p->left;
delete temp;
}
else if (!p->left)
{
temp = p;
p = p->right;
delete temp;
}

// for nodes with two children
else
{
temp = p->right;
while (temp->left)
temp = temp->left;
temp->left = p->left;
temp = p;
p = p->right;
delete temp;
}
}

这是我在构造函数中发现的错误,我发布的上述所有代码都可以正常工作。

    // bad constructor
IntBST()
{ root - NULL; }

// good constructor
IntBST()
{ root = NULL; }

最佳答案

我认为问题在于 temp 保存了另一个对象指向的对象的地址。

也就是说,当你试图删除temp时,temp地址中存储的内存被p的parent所引用;它将存储在 temp 中的地址定义的内存位置标记为保留。因此,当您执行以下操作时:delete temp; 您会遇到段错误,因为您正试图删除保留的内存。

在尝试删除之前,我会尝试将父级设置为指向 null,看看它是否有效。

关于c++ - 当我尝试删除不存在的值时,为什么删除操作会出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44318722/

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