c++ - 在结构中访问 std::list 会引发段错误

标签 c++ memory-management struct constructor malloc

我目前无法从以下程序中找到段错误的来源。

struct info
{
    std::list<int> bfs;
    int *level;
    int *distance;
};

 ...

info* Graph::BFS(int s)
{
    info *tmp = (info*) malloc(sizeof(struct info));
    tmp->level = new int[V];
    tmp->distance = new int[V];

    ...

    tmp->bfs.push_back(s); !! <- causes a segmentation fault
    tmp->level[s] = 0; <- seems to work ok

    int current;
    std::list<int>::iterator i;
    while (!myqueue.empty())
    {
        current = myqueue.front();
        myqueue.pop();
        tmp->bfs.push_back(current); <- causes segmentation fault

     ....

    return tmp;
}

我也尝试过以下操作,但没有成功:

info *tmp = (info*) malloc(sizeof(struct info));
std::list<int> bsf;
tmp->bsf = bsf // and then call tmp->bsf.push_back()....

最佳答案

问题在于混合使用 C++ 代码和 C 代码。

在这个声明中

info *tmp = (info*) malloc(sizeof(struct info));

为结构分配内存而不调用其数据成员的构造函数,

而不是 malloc你必须使用运算符 new .否则数据成员 std::list<int> bfs;不会 build 。

关于c++ - 在结构中访问 std::list 会引发段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46229391/

相关文章:

c++ - 如何初始化 C++ 结构中的内置数组

dictionary - golang - 如何在结构中初始化映射字段?

c++ - 字符数组中的十六进制在写入套接字时导致随机字符

java - 计算获胜几率 - 扑克机器人

java - 将大量数据加载到内存时会增加 permsize

android - 为什么Android Logcat运行应用时总是显示GC_CONCURRENT FREED和GC_CONCURRENT ALLOCATE?

无法为带有数字的结构创建名称

c++ - unique_ptr、自定义删除器和零规则

c++ - 如何使数组包含从基类继承的类

c++ - 在 C++ 中组织命令的最佳方式