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

Segmentation fault on assigning empty string

本文关键字:分段 错误 字符串 分配      更新时间:2023-10-16

这是我尝试运行的代码 -

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;

在C++中,你永远不应该使用 malloc 来分配带有构造函数的对象。malloc函数仅分配内存,但不会导致调用构造函数。

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

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

node* t = new node;