【问题标题】:Segmentation fault on assigning empty string分配空字符串时出现分段错误
【发布时间】:2017-03-25 12:38:50
【问题描述】:

这是我要运行的代码 -

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;

【问题讨论】:

  • The Definitive C++ Book Guide and List挑选一本书。​​
  • 看起来像是学习C而不是C++的案例。 typedef struct 表明了这一点。在C++ 中,不需要typedef struct,只需struct node { string str; };,下面的答案中涵盖了使用malloc
  • Eeeek,这看起来更像是用 C++ 编译器编译的 C,而不是正确的 C++。不要使用malloc 并打破typedef struct 的习惯。

标签: c++ string segmentation-fault


【解决方案1】:

在 C++ 中,您应该从不使用malloc 来分配具有构造函数的对象。 malloc 函数只分配内存,不会调用构造函数。

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

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

node* t = new node;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多