c++ - 分段故障

标签 c++ stl segmentation-fault

试图追踪,但没有找到以下代码在 VC++ 中给出“访问冲突”以及在 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();
}

最佳答案

为什么你认为它应该有效?您使用 malloc,而不是 new,因此不会调用构造函数,并且您所做的一切都会访问未初始化的内存。

关于c++ - 分段故障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15296376/

相关文章:

c - 线程访问静态变量导致段错误

c++ - 有没有办法逐个元素地清除缓冲区?

c++ - 在终止值 C++ 之前查找序列的最后一个值

c++ - 通过构造函数转换容器

c++ - std::map find_if 条件样式混淆

image - Image::ValidJpeg 和内存文件的段错误

c - Valgrind:1.strcpy 的读取大小无效

c++ - 解析 wavefront obj 文件格式

c++ - 如何在 C++ 中使用带有自定义排序成员函数的 sort()?

c++ - 将元素插入 map 的推荐方法