[英]Deleting from a Binary Search Tree?
I'm trying to delete from a binary search tree and keep getting this error in debugger and am not sure what to do to correct it. 我正在尝试从二叉搜索树中删除,并在调试器中不断收到此错误,并且不确定如何纠正它。 Is this code correct? 此代码正确吗?
Program received signal EXC_BAD_ACCESS, Could not access memory. 程序收到信号EXC_BAD_ACCESS,无法访问内存。 Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000 0x00007fff8cc17fe2 in std::string::compare () 原因:在地址:0x0000000000000000 0x00007fff8cc17fe2在std :: string :: compare()中的KERN_INVALID_ADDRESS
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;
}
}
First, compile this with debug settings, then run it under a debugger . 首先,使用调试设置进行编译,然后在调试器下运行它 。 I can all-but-guarantee it will trip exactly where your failure case is. 我可以保证一切,但它会完全解决您失败案例的位置。
On that note, I speculate it is this line : 关于这一点,我推测这是这一行:
if(x < t->element) // <==== here
{
remove(x, t->left);
}
else
{
remove(x, t->right);
}
For some reason your logic before this takes the following deductions: 由于某种原因,在此之前您的逻辑需要进行以下推导:
You don't account for the case when both left and right are null, such as would be the case in a tree leaf node. 你不解释的情况下,当左 ,右都为空,如将是一个树的叶节点的情况。 Consequently this, taken from your else condition: 因此,这取自您的else条件:
BinaryNode *oldNode = t;
t = ( t->left != NULL ) ? t->left : t->right;
delete oldNode;
cout << "Successly deleted!" << endl;
In the case of a leaf node, will leave t
set to null, which is immediately dereferenced by the code at the beginning of this answer. 如果是叶节点,则将t
设置为null,此代码将在此答案的开头立即将其取消引用。
You need to rework your logic for this, and if code prior to a dereference can invalidate the pointer being dereferenced, you need to check it first . 您需要为此重新设计逻辑,并且如果取消引用之前的代码可以使被取消引用的指针无效,则需要首先对其进行检查。
Finally if you're wondering what the hint was that is the offending line, the specific error your getting reports string comparison is dereferencing a null ptr. 最后,如果您想知道那是有问题的行的提示,则您得到报告字符串比较的特定错误是取消引用空ptr。 String comparison isn't done anywhere else in this function except through that operator <
overload. 除了通过该operator <
重载,字符串比较不会在此函数的其他任何地方进行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.