AHm*_*Net 1 c++ memory pointers allocation assign
我试图使用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;
}
Run Code Online (Sandbox Code Playgroud)
我尝试了一个简单的assigne(node-> data ="string"),但我遇到了同样的问题请帮忙!
用C++忘了malloc().如果要分配对象使用new:
node * n = new node; // or if your variable should be called node
// you'd need new struct node to disambiguate
Run Code Online (Sandbox Code Playgroud)
问题malloc()是它只是分配未初始化的内存.它不能确保对象创建的C++语义.因此,节点内的字符串不会被初始化为有效状态.这会导致将此字符串赋值为UB.
如果你真的需要malloc()在C++中使用,那么你需要在之后使用一个新的位置来将对象初始化为一个有效的状态(在线演示).
void *p = malloc(sizeof(node)); // not so a good idea !
node *n2 = new (p)node; // but ok, it's feasible.
Run Code Online (Sandbox Code Playgroud)
你不能malloc是一个C++字符串.您应该使用合适的new和delete,至少,这样的构造函数被调用.停止在C++中使用C语言.
理想情况下你甚至不会使用new; 只有一个具有自动存储持续时间的普通对象,或者,如果你迫切需要动态分配,std::make_unique.
2016年无需手动内存管理.