C++二进制树segfault(与类实现)
我一直在尝试在C ++中实现BST,并编写了这些功能以将新节点插入其中。但是,我现在很困难地试图理解为什么此代码会导致segfault。
这可能与我没有将root地址传递给实用程序功能的事实有关,因为当我这样做时,插入功能开始正常工作。但是,我不明白为什么这种特定的实现不起作用。 我真的很感激是否可以澄清
class Bst {
private:
struct bstNode *root;
struct bstNode* insertUtil(int, struct bstNode*);
void delTree(struct bstNode**);
public:
Bst();
~Bst();
void insert(int);
};
/// struct bstNode *root = NULL;
struct bstNode* Bst::insertUtil(int x, struct bstNode *r){
if(r == NULL){
r = newNode(x);
}
if(x < r->data){
r->left = insertUtil(x, r->left);
} else{
r->right = insertUtil(x, r->right);
}
return r;
}
void Bst::insert(int x){
if(root == NULL){
root = newNode(x);
return;
}
insertUtil(x, root);
}
如果您有兴趣, 完整的代码: https://codepen.io/ adrasti/pen/nwyvozy
I've been trying to implement BST in c++ and I wrote these functions to insert new nodes in it. However, I am now quite stuck trying to understand why this code causes segfault.
It probably has something to do with the fact that I'm not passing the address of root to my utility function because when I do, the insert functions start working properly. However, I do not understand why this particular implementation does not work. I would really appreciate if someone could clarify
class Bst {
private:
struct bstNode *root;
struct bstNode* insertUtil(int, struct bstNode*);
void delTree(struct bstNode**);
public:
Bst();
~Bst();
void insert(int);
};
/// struct bstNode *root = NULL;
struct bstNode* Bst::insertUtil(int x, struct bstNode *r){
if(r == NULL){
r = newNode(x);
}
if(x < r->data){
r->left = insertUtil(x, r->left);
} else{
r->right = insertUtil(x, r->right);
}
return r;
}
void Bst::insert(int x){
if(root == NULL){
root = newNode(x);
return;
}
insertUtil(x, root);
}
full code if you're interested: https://codepen.io/adrasti/pen/NWyVOZY
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这是一个逻辑错误。
此行(在
中insertutil
中):因此,程序将执行
或
将执行:永远
不要停止直到出现。
我也在学习C ++,如果我不正确,我希望得到纠正。
I think it's a logic error.
this line(in
insertUtil
):So, program will execute
or
and will alway execute:
never stop until out of memory.
I am also learning C++, and I hope to be corrected if I am not correct.
绝对会错过
bst :: intertutill
您可以通过在该功能中进行小重构来快速的条件
中断 溢出。
如果搜索此操作,您可以将
-fsanitize =地址
flag添加到GCC编译器或用户valgrind
也可以重构代码以成为更多C ++现代风格,但是我可以粘贴它稍后你
Definetly you miss break condition in
Bst::insertUtill
you can quickly by making small refactor in that functionand after that change
Bst::insert
toby doing that you will avoid stack overflow.
In case of searching of that you can add
-fsanitize=address
flag to gcc compiler or uservalgrind
Also you can refactor code to be more C++ modern style but that I can paste you later