分段故障 [英] Segmentation fault
本文介绍了分段故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
试图跟踪,但没有找到一个原因,为什么下面的代码在VC ++中给出访问冲突,并在gcc中的分段错误。
Tried to trace, but did not find a reason why the following code is giving "Access violation" in VC++, and segmentation fault in gcc..
#include <vector>
#include <iostream>
using namespace std;
typedef struct node
{
std::string data;
vector <struct node*> child;
}NODE, *PNODE;
int main()
{
PNODE head;
head = (PNODE) malloc(sizeof(NODE));
head->data.assign("hi");
printf("data %s", head->data.c_str());
getchar();
}
推荐答案
使用 new
而不是 malloc
在堆上创建C ++对象。
Use new
rather than malloc
to create C++ objects on the heap.
:
head = (PNODE) malloc(sizeof(NODE));
应显示
head = new NODE;
原因 malloc()
这里的工作是它不调用对象构造函数。
The reason malloc()
doesn't work here is that it doesn't call object constructors.
这篇关于分段故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文