gpt4 book ai didi

c++ - 包含字符串值的结构在使用动态内存分配创建后在分配时导致段错误

转载 作者:可可西里 更新时间:2023-11-01 18:15:52 25 4
gpt4 key购买 nike

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

#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;
}

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

它的工作方式如下:

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;
}

然后在主函数中:

int main() {
Node n2 = initNode("Hello");
cout << n2.data << endl;
}

最佳答案

这是行不通的,因为您实际上并没有将 Node 实例构建到您 malloc 的内存中。

您应该改用 new:

Node *n = new Node{};

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

new 分配内存构造类的一个实例。

关于c++ - 包含字符串值的结构在使用动态内存分配创建后在分配时导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29095923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com