看不出为什么这是段错误
Can't see why this is segfaulting
class Node {
private:
Node *left = NULL, *right = NULL;
char data;
public:
Node(char new_data) {
data = new_data;
}
Node *get_left() {
return left;
}
Node *get_right() {
return right;
}
char get_data() {
return data;
}
void set_data(char new_data) {
data = new_data;
}
};
我已经调试了它(使用 gdb 和 cout(,似乎set_data函数是问题所在。为什么?
还有更多的代码,但我假设不需要更多的代码。
编辑:
class tree {
private:
Node *root;
public:
tree(char ch) {
cout << "ASDASD"; //using this to identify error
root->set_data(ch);
cout << root->get_data(); //using this to identify error
}
};
编辑2:
#include <iostream>
#include "tree.h"
#include <cctype>
using namespace std;
int main () {
char c;
cout << "Enter a series of letters: ";
cin >> c;
tree t(c); //sets first one to root
while(cin) { //change??
cin >> c;
if (isdigit(c)) break;
Node *n;
n->set_data(c);
t.insert(n);
}
}
代码应该从键盘读取,直到读取数字。它读取所有字母,但是当我键入一个数字以尝试退出时,它会出现段错误。
class tree {
private:
Node *root;
public:
tree(char ch) {
cout << "ASDASD"; //using this to identify error
root->set_data(ch); // **HERE**
cout << root->get_data(); //using this to identify error
}
};
在这一点上,root
没有指向任何东西。因此,尝试取消引用它是一个错误。在使用指针指向的事物之前,必须使指针指向某物。
你在这里有同样的问题:
Node *n;
n->set_data(c);
set_data
函数用于设置Node
的数据。所以你必须已经有一个Node
来调用它。你没有在任何地方创建一个Node
,n
在这里没有指向一个。
相关文章:
- 为什么PyImport_ImportModule python 3.7.2 中出现段错误?
- 为什么在访问 vtkRenderWindow 的"交互器"变量时会发生段错误?
- 全局向量导致 C++ 程序结束时出现段错误
- 为什么重载运算符<<打印特征类成员会导致段错误?
- 更改条件段错误
- 使用 TTF_RenderText() 加载字体时获取段错误 TTF_OpenFontRW()
- 注册对对象工厂的调用会导致段错误
- pthread_create在构造函数段错误中
- Nanoflann发现邻居提出段错误
- C++ 中的构造函数、继承、堆栈、堆、this-pointer 和段错误
- 具有unique_ptr的 CRTP 会导致段错误
- 增强纤维work_stealing屏障会导致段错误
- 当我返回指向结构的指针向量时出现段错误
- C++为什么我的代码没有爆炸/段错误?
- Pthread段错误,使用指向main中变量的指针
- C++ 模板中的段错误
- 相当于Windows/MSVC上的段错误?
- 为什么我的 LLVM JIT 实现出现段错误?
- 为什么访问我的引用捕获变量会导致我的 lambda 函数出现段错误?
- 为什么自删除的全局 Vulkan 实例仅在添加层时才导致段错误?