[英]Why does assigning a 'char' to a 'char' give a seg fault? C++
I have a class that looks like this: 我有一堂课,看起来像这样:
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
};
However, when I go to assign Data
a value, I receive a seg fault. 但是,当我为
Data
赋值时,会出现段错误。 I do this like: 我这样做:
root->childT->Data = p_data;
Where p_data
is a char = t
and root
is a pointer created by myTreeNode *root = new myTreeNode;
其中
p_data
是char = t
而root
是由myTreeNode *root = new myTreeNode;
创建的指针myTreeNode *root = new myTreeNode;
. 。 Why when going to assign
Data
a value would I get a seg fault? 为什么在给
Data
赋值时会出现段错误? Isn't it just the same as doing char Data = 't'
? 这与做
char Data = 't'
吗?
Your children are not pointing to any memory location. 您的孩子没有指向任何内存位置。 You have only created a new instance for the root node.
您只为根节点创建了一个新实例。 You are getting a segfault because you are dereferencing a null pointer.
由于正在取消引用空指针,因此出现了段错误。
For example: 例如:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.