包含字符串值的struct在使用动态内存分配创建后,在分配时会导致分段错误

Dhw*_*nit 7 c++ string struct memory-management dynamic-memory-allocation

编译器在以下代码上抛出运行时段错误:

#include <iostream>
#include <string>
using namespace std;

struct Node{
  int data;
  void *next;   
  string nodeType;
};

Node* initNode(int data){
  Node *n = (Node*)malloc(sizeof(Node));
  n->data = data;
  n->next = NULL;
  n->nodeType = "Node";   //if this line is commented it works else segfault
  return n;
}

int main() {
  Node *n1 = initNode(10);
  cout << n1->data << endl;
}
Run Code Online (Sandbox Code Playgroud)

有人可以解释为什么字符串赋值在动态分配的结构中不起作用,在静态分配的情况下,为什么它有效?

它的工作方式如下:

Node initNode(string data){
  Node n;
  n.data = data;  //This works for node creation statically
  n.next = NULL;
  n.nodeType = "Node";  //and even this works for node creation statically
  return n;
}
Run Code Online (Sandbox Code Playgroud)

然后在主要功能:

int main() {
  Node n2 = initNode("Hello");
  cout << n2.data << endl;
}
Run Code Online (Sandbox Code Playgroud)

Tar*_*ama 8

这不起作用,因为你实际上并没有在你Node的内存中构造一个实例malloc.

您应该使用new:

Node *n = new Node{};
Run Code Online (Sandbox Code Playgroud)

malloc只分配内存,它不知道一个类是什么或如何实例化一个.通常不应该在C++中使用它.

new分配内存构造类的实例.