分段错误:BST C++代码中的 11

segmentation fault: 11 in C++ code BST

本文关键字:代码 C++ 错误 BST 分段      更新时间:2023-10-16
# include <iostream>
using namespace std;
struct node{
int data;
node *l,*r,*p;
};
int main(){
int i,n;
cout<<"Enter the number of nodesn";
cin>>n;

i=1;

while(i<=n){
y=root;
x = (node *)malloc(sizeof(node));
cin>>x->data;

while(y!=NULL){

if(x->data < y->data){
parent = y;
y  =  y->l;
}

else{
parent = y;
y = y->r;
}

} 
if(root==NULL){
root=x;
}
else if(parent->data < x->data){
parent->r = x;
x->p = parent;
}
else{
parent->l = x;
x->p = parent;
}
i++;
}

return 0;
}

它使用 g++ 命令通过命令窗口在 iMac 上给出分段错误,但在其他 IDE(在线和离线 IDE(上运行良好,我什至在我的 fiends 个人计算机上尝试了代码,他有 DEV c++,并且可以正常工作,我还尝试了在线 IDE(网站:-codechef, 等,工作得很好(.在此处输入图像描述

假设您有减量node *x,*y,*root,*parent;(如您在对另一个答案的注释中所述(,则变量root是未初始化的。因此,任何使用它的尝试都是未定义的行为,因此您的程序可能会崩溃(或可能不会崩溃(。您所看到的(有时程序有效,有时无效(是非常典型的未初始化变量。试试这个

node* root = NULL;