我目前无法从以下程序中找到段错误的来源。
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/