【发布时间】:2016-11-19 19:14:16
【问题描述】:
我正在尝试使用 g++ 5.1 编译和执行这个小 c++ 代码,它编译得很好,当我在 linux 上执行它时,我收到这个错误消息:“Segmentation fault (core dumped)”。
但是相同的代码在 osx 上可以正常运行,但在 linux 上却不行:
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
struct node {
std::string data;
};
int main() {
struct node * node = (struct node * )
malloc(sizeof(struct node));
node->data.assign("string");
// node->data = "string" --> same issue
return 0;
}
我尝试了一个简单的分配 (node->data = "string"),但我遇到了同样的问题任何帮助!
【问题讨论】:
-
为什么在 C++ 代码中使用
malloc?new将初始化字符串对象 -malloc不会。 -
谁一直在教这种东西?那些人难道没有想到80年代已经结束了吗? ://
-
扩展@EdHeal 所说的内容:仅分配 sizeof(struct node) 字节然后开始使用它们是不够的。您必须确保字符串对象的构造函数也运行,以便正确初始化节点对象的私有状态。为此,您需要使用 new 运算符(例如 node = struct node * node = new node; )
-
顺便说一句,看看链接的问题,它可能不是一个骗局,但至少高度相关。
-
在编程中,“代码”从不使用“s”复数。你会永远说“代码”。 (当人们这样做时,它在语法上是不正确的)
标签: c++ pointers memory allocation assign