C++ C++;分段错误(核心转储)
所以我遇到的问题是分割错误。 我正在尝试实现一个AVLtree,我相信这部分代码就是问题所在,但我无法指出我做错了什么 我的AVLtree课程的一部分:C++ C++;分段错误(核心转储),c++,segmentation-fault,avl-tree,C++,Segmentation Fault,Avl Tree,所以我遇到的问题是分割错误。 我正在尝试实现一个AVLtree,我相信这部分代码就是问题所在,但我无法指出我做错了什么 我的AVLtree课程的一部分: Node* AVLtree::findNode(string cityID){ Node *thisNode = this->rootNode; while(thisNode!=0){ if(thisNode->getCity()->getName().compare(c
Node* AVLtree::findNode(string cityID){
Node *thisNode = this->rootNode;
while(thisNode!=0){
if(thisNode->getCity()->getName().compare(cityID)==0){return thisNode;
}else if(thisNode->getChildR()->getCity()->getName() < cityID){ thisNode = thisNode->getChildR();
}else{thisNode = thisNode->getChildL();}
}
return this->rootNode;
}
对不起,如果这是一个简单的错误,但是我对C++是新的,需要时间和实践来学习:
提前谢谢
(请注意,如果您需要更多的代码,请询问)在您的代码中,您似乎检查当前节点是否为空,但在访问它之前,您没有检查子节点是否为空:
while(thisNode!=0) {
// ...
if(thisNode->getChildR()->getCity()->getName() < cityID){
^^^^^^^^^^^
here
while(thisNode!=0){
// ...
如果(thisNode->getChildR()->getCity()->getName()
问题可能与您没有检查方法是否返回propper指针有关。如果您试图在无效指针上调用方法,将导致分段错误
就你而言:
如果
thisNode->getChildR()
实际上没有返回有效指针,则调用getCity()
进行核心转储。非常感谢!我现在已经对它进行了排序,确保它检查节点是否为空。再次感谢!@Student38068:正确的解决方法可能是在此时不查看子节点!您想根据thisNode->getCity()->getName()决定走哪条路
:如果这是要查找的名称,则您已经找到了节点。如果名称大于要查找的城市,则从左侧往下走,否则从右侧往下走!那么,它会是这样的吗?node*thisNode=this->rootNode;while(thisNode!=0){If(thisNode==0){break;}//当thisNode为空时使用。int location=thisNode->getCity()->getName().compare(cityID);if(location==0){return thisNode;}else if(location>0){thisNode=thisNode->getChildR();}else{thisNode->getChildL();}code
@Student38068:这更像它通常的样子!我认为您的方法节点位于右子节点的左子树中,无法连接到该节点。@Student38068:抱歉,缺少一个原始代码:使用问题中的原始代码,您无法查看右子节点的左子树(画一张树的图片,其中根的右子级的左子级具有您要查找的名称:您不会使用原始代码;我认为您将使用修改后的代码)。
$ ./mainTest
TEST 1: AVLtree with city paramter of city1 (BoomTown)
Segmentation fault (core dumped)
while(thisNode!=0) {
// ...
if(thisNode->getChildR()->getCity()->getName() < cityID){
^^^^^^^^^^^
here