1

我正在尝试从二叉搜索树中删除并在调试器中不断收到此错误,并且不确定如何纠正它。这段代码正确吗?

程序收到信号 EXC_BAD_ACCESS,无法访问内存。原因:KERN_INVALID_ADDRESS 地址:0x0000000000000000 0x00007fff8cc17fe2 in std::string::compare ()

void remove( const Comparable & x, BinaryNode *& t )
{
    if (t != NULL)
    {
        if(t->element.find(x) != std::string::npos)
        {
            if( t->left != NULL && t->right != NULL ) // Two children
            {
                t->element = findMin( t->right )->element;
                remove( t->element, t->right);
            }
            else
            {
                BinaryNode *oldNode = t;
                t = ( t->left != NULL ) ? t->left : t->right;
                delete oldNode;
                cout << "Successly deleted!" << endl;
            }
        }
        if(x < t->element)
        {
            remove(x, t->left);
        }
        else
        {
            remove(x, t->right);
        }
    }
    else 
    {
        cout << x << "<-could not delete?" << endl;            
    }     
}
4

1 回答 1

1

首先,使用调试设置编译它,然后在调试器下运行它。我几乎可以保证它会准确地跳到您的失败案例所在的位置。

在那张纸条上,我推测是这条线:

if(x < t->element)  // <==== here
{
    remove(x, t->left);
}
else
{
    remove(x, t->right);
}

出于某种原因,您在此之前的逻辑需要以下推论:

  • 左边和右边都不为空
  • 只有左或右为空

您不考虑左右都为空的情况,例如在树叶节点中的情况因此,这取自您的 else 条件:

BinaryNode *oldNode = t;
t = ( t->left != NULL ) ? t->left : t->right;
delete oldNode;
cout << "Successly deleted!" << endl;

在叶节点的情况下,将保留t设置为 null,此答案开头的代码会立即取消引用。

您需要为此重新设计逻辑,如果取消引用之前的代码会使被取消引用的指针无效,则需要先检查

最后,如果您想知道有问题的行的提示是什么,那么您获取报告字符串比较的具体错误是取消引用空 ptr。operator <除了通过该重载之外,此函数中的其他任何地方都不会进行字符串比较。

于 2013-10-19T07:13:06.320 回答