为什么要分配一个' char'到了一个' char'给出一个段错误? C ++

时间:2016-03-30 15:46:53

标签: c++ segmentation-fault

我有一个看起来像这样的课程:

class myTreeNode
{
     public:   
        char Data;
        myTreeNode *childA = NULL;   //A's always go in child1
        myTreeNode *childT = NULL;   //T's always go in child2
        myTreeNode *childC = NULL;   //c's always go in child3
        myTreeNode *childG = NULL;   //G's always go in child4
};

然而,当我去分配Data一个值时,我收到一个seg错误。我这样做:

root->childT->Data = p_data;

其中p_datachar = t,而root是由myTreeNode *root = new myTreeNode;创建的指针。为什么在分配Data值时会出现seg错误?它与执行char Data = 't'只是一样吗?

1 个答案:

答案 0 :(得分:4)

您的孩子没有指向任何记忆位置。您只为根节点创建了一个新实例。您正在获取段错误,因为您正在取消引用空指针。

例如:

class myTreeNode
{
public:
  char Data;
  myTreeNode *childA = NULL;   //A's always go in child1
  myTreeNode *childT = NULL;   //T's always go in child2
  myTreeNode *childC = NULL;   //c's always go in child3
  myTreeNode *childG = NULL;   //G's always go in child4
};

int main()
{
  // allocate memory
  myTreeNode *root = new myTreeNode;
  root->childT = new myTreeNode; // allocate child

  root->childT->Data = 'a';

  // delete allocated memory
  delete root->childT;
  delete root;
  return 0;
}