【发布时间】:2018-02-25 19:05:47
【问题描述】:
我试图在 C++ 中实现一个简单的二叉树,但是指针给我带来了麻烦。尽管我从未为指针分配结构,但它不会评估为 NULL,因此,实际上从未分配过,一切都会中断。
代码:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
struct BTNode {
int data;
BTNode *left;
BTNode *right;
};
int main() {
BTNode *tree;
srand(time(NULL));
int input[11];
for(int i=0;i<11;i++) {
input[i] = 1 + rand()%50;
}
for(int i=0;i<11;i++) { //populate binary tree
cout << "Populating tree " << i << "\n";
if(!tree) {
tree = new BTNode();
cout << "Initialising tree\n";
tree->data = input[i];
} else {
cout << "Setting tree pointer\n";
BTNode *curnode = tree;
while(true) {
if(curnode->data >= input[i]) {
if(!curnode->left) {
curnode->left = new BTNode();
curnode->left->data = input[i];
cout << "Put " << input[i] << " in left node of " << curnode->data << ".\n";
break;
}
else {
cout << "Moving on to left node...\n";
curnode = curnode->left;
}
}
else {
if(!curnode->right) {
curnode->right = new BTNode();
curnode->right->data = input[i];
cout << "Put " << input[i] << " in right node of " << curnode->data << ".\n";
break;
}
else {
cout << "Moving on to right node...\n";
curnode = curnode->right;
}
}
}
}
}
}
给出输出
Populating tree 0
Setting tree pointer
Moving on to right node...
Segmentation fault (core dumped)
【问题讨论】:
-
您回答了自己的问题。它没有被初始化。特别是,它还没有被初始化为 NULL。从任何未初始化的变量中读取都是未定义的行为,指针不是特例。
标签: c++ pointers segmentation-fault