简体   繁体   中英

segmentation fault: 11 in C++ code BST

# 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;
}

it is giving the segmentation error on iMac through the command windows using the g++ command, but works fine on other IDE's (both online and offline IDE),i even tried the code on my fiends personal computer he has DEV c++ and it works fine on it,I also tried on an online IDE (websites:-codechef, etc and worked just fine ). enter image description here

Assuming you have the decalration node *x,*y,*root,*parent; (as you stated in the comment to the other answer) then the variable root is unintialised. Therefore any attempt to use it is undefined behaviour and therefore your program might crash (or might not). What you are seeing (sometimes the program works and sometimes it doesn't) is very typical of uninitialised variables. Try this

node* root = NULL;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM