C++ 分配空字符串时出现分段错误

C++ 分配空字符串时出现分段错误,c++,string,segmentation-fault,C++,String,Segmentation Fault,下面是我正在尝试运行的代码- typedef struct node{ string str; }node; string s = ""; node *t = (node *)malloc(sizeof(node)); t->str = s ; // if s is empty, this statement gives segmentation fault. cout<<t->str<<endl; typedef结构节点{ 字符串str; }节点

下面是我正在尝试运行的代码-

typedef struct node{
  string str;
}node;

string s = "";

node *t = (node *)malloc(sizeof(node));
t->str = s ; // if s is empty, this statement gives segmentation fault.

cout<<t->str<<endl;
typedef结构节点{
字符串str;
}节点;
字符串s=“”;
node*t=(node*)malloc(sizeof(node));
t->str=s;//如果s为空,则该语句给出分段错误。
C++中的CUT

不应该使用<代码> MalOC 用构造函数分配对象。

malloc
函数只分配内存,但不会导致调用构造函数

这意味着您的
str
成员未初始化,您在使用它时有未定义的行为

如果您确实需要动态分配,请改用
new

node* t = new node;

从中选择一本书。看起来像是学习
C
而不是
C++
typedef结构
表明了这一点。在
C++
中,不需要
typedef struct
,只需要
struct节点{string str;},使用<代码> MalOC 被覆盖在下面的答案中。EEEK,看起来更像是用C++编译器编译的,而不是C++。不要使用
malloc
并打破那种
typedef结构的习惯。