看不出为什么这是segfaulting

时间:2016-04-17 23:34:11

标签: c++ nodes

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

代码应该从键盘读取,直到读取数字。它会读取所有字母,但是当我键入一个数字以尝试退出时,会出现段错误。

1 个答案:

答案 0 :(得分:1)

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并未指向此处。{/ p>