我试图将字符串变量的值分配给结构的另一个字符串变量 . 但是gdb给出了运行时错误 . 错误如下:程序接收信号SIGSEGV,分段故障 . 来自/ usr / lib / i386-linux-gnu / libstdc .so.6的std :: string :: assign(std :: string const&)()中的0xb7f7c8f8
我的C程序是:
#include<iostream>
#include<stdlib.h>
#include<string>
typedef long unsigned int LUI;
using namespace std;
struct graph {
string string_node;
LUI node;
struct graph *link;
};
struct graph *abc[30];
struct graph *t;
string x;
int main() {
t = (struct graph *) malloc(sizeof(struct graph *));
x = "abc";
t->string_node = x;
t->link = NULL;
abc[0] = t;
cout << "Value is " << abc[0]->string_node << endl;
cout << "end";
return 0;
}
请帮我把x的值存入t-> string_node . 提前致谢..
2 回答
你的问题是你正在用
malloc
分配一个struct
,但是struct
只有POD(普通旧数据)成员:它有一个std::string
成员,而std::string
对象希望被构造 . 简单地使用malloc
为其分配内存将不会调用std::string
构造函数,因此稍后尝试与该std::string
进行交互将导致未定义的行为,因为该对象处于错误状态 .您应该使用
new
来分配struct
,这将正确分配内存并为每个成员调用默认构造函数 . (相反,您应该使用delete
而不是free
释放该内存,以正确调用每个成员的析构函数 . )或者,可以使用"placement new"在已经分配的内存中构造一个对象,但这不是您通常需要做的事情 .
graph
是一个 class . 它包含C类,特别是它包含std::string
.必须使用
new
运算符在动态范围内构造所有C类 . 它们不能用C库函数malloc()
构造,它对C类完全没有任何意义 . 这样做会导致未定义的行为(更不用说你的malloc-ed大小是错误的) .现在您正在编写C代码,您需要完全忘记
malloc()
,realloc()
和free()
曾经存在过,并始终使用new
和delete
.