【问题标题】:segmentation fault: 11 in C++ code BST分段错误:C++ 代码 BST 中的 11
【发布时间】:2019-01-22 03:20:59
【问题描述】:
# include <iostream>
using namespace std;

struct node{

int data;
node *l,*r,*p;

 };

 int main(){

int i,n;

cout<<"Enter the number of nodes\n";
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;
}

它在 iMac 上使用 g++ 命令通过命令窗口给出分段错误,但在其他 IDE(在线和离线 IDE)上工作正常,我什至在我的恶魔个人电脑上尝试了代码,他有 DEV c++ 和它工作正常,我还尝试了在线 IDE(网站:-codechef 等,工作正常)。enter image description here

【问题讨论】:

标签: c++ command g++ binary-search-tree


【解决方案1】:

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

node* root = NULL;

【讨论】:

  • 它甚至没有被声明为更少定义。变量parentx 也不是,可能更多。由于显示的代码甚至不会构建,因此尝试发布答案是毫无意义的。
  • @Someprogrammerdude 在 cmets 的另一个答案中,OP 声明他添加了声明。这就是我回答的依据。
猜你喜欢
  • 2012-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多