访问std :: list instruct struct诱导segfault

accessing std::list inside struct induce segfault

本文关键字:诱导 segfault struct list std 访问 instruct      更新时间:2023-10-16

我当前找不到以下程序的分割故障的来源。

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;将不会构造。