使用 cout 访问对象成员会导致段错误
Accessing objects member with cout causes segfault
我正在尝试创建一个用于练习的二叉搜索树。 我已经在底部向此树中添加了一些节点,但是当我想通过主函数中的cout检查这些节点及其成员时,我收到segFault错误。 但是奇怪的是,我可以分配这些成员,但我没有收到此问题。
如果有人能帮助我理解为什么cout会导致这种情况,那么将不胜感激。 谢谢。
编辑:如果它有帮助,即使我在实例化根值后不更改根值,也会发生这些段错误。
#include <iostream>
using namespace std;
class Node{
public:
Node(){
}
Node(int someNum){
data = someNum;
}
int data;
Node *right;
Node *left;
};
class BinarySearchTree{
public:
Node *root;// = new Node();
BinarySearchTree(int rootValue);
void insertNode(Node *aNode, int nodeValue);
};
BinarySearchTree::BinarySearchTree(int rootValue){
if(root != NULL){
root->data = rootValue;
root->left = NULL;
root->right = NULL;
}
}
void BinarySearchTree::insertNode(Node *aNode, int nodeValue){
if(nodeValue<(aNode->data)&&aNode->left==NULL){ //If it's less than and left child doesn't exist
cout<<"first"<<endl;
Node *newNode = new Node(nodeValue); //Create a new node with that value
aNode->left = newNode;
}
else if(nodeValue<(aNode->data)&&aNode->left!=NULL) //If it's less than and left child DOES exist
{
cout<<"second"<<endl;
insertNode(aNode->left, nodeValue); //Recursively travel to the left
}
else if(nodeValue>=(aNode->data)&&aNode->right==NULL){
cout<<"third"<<endl;
Node *newNode = new Node(nodeValue);
aNode->right = newNode;
}
else{
cout<<"fourth"<<endl;
insertNode(aNode->right, nodeValue);
}
}
int main()
{
BinarySearchTree bst(10);
bst.insertNode(bst.root, 5);
bst.insertNode(bst.root, 3);
bst.insertNode(bst.root, 12);
bst.root->data = 15; //No segFault
cout<<"bst.root->data is "<<bst.root->data<<endl; //Why does this cause a segFault? And why does it prevent other stuff from printing out?
cout<<"bst.root->right is "<<bst.root->right<<endl; //Why does this cause a segFault?
cout<<"bst.root->left is "<<bst.root->left<<endl; //Why does this cause a segFault?
return 0;
}
第一个明显的错误是BinarySearchTree
构造函数中的错误:
if(root != NULL){
root->data = rootValue; // undefined behavior
root
未初始化,因此它包含任何垃圾值。 然后,当您使用该垃圾值(root->data
)时,您的程序已经进入了未定义行为的状态。
相关文章:
- 编写代码时C++出现错误:错误 1 错误 C2601:'circle':本地函数定义是非法的
- 如何摆脱C ++中的分段错误错误?
- Clang 8 带有静态 constexpr 和数组的链接器错误 - 错误是什么以及如何解决它?
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- 如何解决分段错误错误C++
- 作为参数模板的模板类:MSVC 错误 - 错误 C2977:模板参数过多 (C++98)
- 安卓工作室 |CPP 文件错误错误: 位图库中对"AndroidBitmap_unlockPixels"的未定义引用
- 卷曲给出分段错误错误
- 无法访问 Arduino 结构字段。错误"退出状态 1。xxxx 不命名类型"
- 错误错误 C2872:"布尔值":kinect.h 的不明确符号
- C++打印模板容器错误(错误:"运算符<<"的不明确重载)理解?
- 结构的分割错误错误
- 为什么此代码返回分段错误错误?
- 错误错误:无法编译内置功能
- 分段错误错误C++
- C++ 1Z 错误:错误:演绎指南中声明中的显式限定
- 使用对数据类型的向量的哈希表中的分段错误错误
- 为什么此代码会导致分段错误错误
- JNA结构字段值错误
- C++段故障错误