分段错误:BST C++代码中的 11
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 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;
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 在Linux for Windows上编译C++代码时出错
- 我的字符计数代码计算错误.为什么
- 孤立代码块在结构中引发异常
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 此代码是否违反一个定义规则
- 为什么我的代码在输出中增加了93天
- 我的简单if-else语句是如何无法访问的代码
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 为什么在这个代码结束循环中没有得到结束
- 在c代码之间共享数据的最佳方式
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值