2017-09-14 50 views
1

我目前無法從以下程序中找到段錯誤的來源。訪問結構中的std :: list導致段錯誤

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().... 
+3

請勿使用'malloc'。 – BLUEPIXY

+0

爲什麼不呢?我應該只用新的? –

+0

作爲創建'std :: list '的方法不正確。 – BLUEPIXY

回答

4

的問題是在混合C++代碼與C語言代碼。

在這份聲明中

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

內存是爲結構分配,而不調用其數據成員的構造函數,

而不是malloc你必須使用運營商new。否則數據成員std::list<int> bfs;將不會構建。