0

CLRS에 설명 된 BFS 알고리즘을 구현하려고합니다. 나는 그러나이 프로그램을 실행할 때 큐가 초기화 될 때C++ : 포인터 큐를 초기화 할 때 segfault 얻기

#include <iostream> 
#include <list> 
#include <queue> 
#include <string> 
#include <sstream> 
using namespace std; 
struct Node{ 
    char colour; 
    int numNbr; 
    Node* parent; 
    int distance; 
    int* neighbours; 
    int* costs; 
    int name; 
    Node(int _numNbr,int _name){ 
     name = _name; 
     colour = 'w'; 
     parent = 0; 
     distance = -1; 
     neighbours = new int[_numNbr]; 
     costs  = new int[_numNbr]; 
     numNbr = _numNbr; 
    } 
}; 

list<Node*> bfs(Node** &nodes,int numNodes,int startNode) { 
    cout << "performing BFS\n"; 
    for(int i = 0; i < numNodes;i++) { 
     nodes[i]->colour = 'w'; 
     nodes[i]->parent = 0; 
    } 
    cout << "All nodes painted white" <<endl; 
    queue<Node*> q; // segfault occurs here 
    cout << "initialised a queue" << endl; 
    list<Node*> l; 
    cout << "initialised a list" << endl; 
    nodes[startNode]->colour = 'g'; 
    nodes[startNode]->distance = 0; 
    q.push(nodes[startNode]); 
    Node* u; 
    Node* v; 
    while(!q.empty()){ 
     u = q.front(); 
     for(int i = 0;i < u->numNbr; i++) { 
      v = nodes[u->neighbours[i]]; 
      if(v->colour == 'w'){ 
       v->colour = 'g'; 
       v->distance = (u->distance)+1; 
       v->parent = u; 
       q.push(v); 
      } 
     } 
     l.push_front(u); 
     u->colour = 'b'; 
     q.pop(); 
    } 
    return l; 
} 

int main(){ 
    int nodeCount; 
    cin >> nodeCount; 
    cin.ignore(); 
    Node** nodes = new Node*[nodeCount+1]; 
    for(int i = 0; i < nodeCount; i++){ 
     .... // build up the nodes in the adjacency list 
    } 
    list<Node*> l = bfs(nodes,nodeCount,1); 
    cout << "BFS of nodes\n"; 
    for(list<Node*>::iterator it = l.begin();it != l.end();it++){ 
     cout << (*it)->name << " "; 
    } 
    cout << endl; 
    return 0; 
} 

, 나는 단지 segfault 다음에 다음과 같은 출력을 얻을 : 나는 다음과 같은 명령을 사용하여 컴파일하고

[email protected]:~/Code/cpp/dijkstra$ ./dijkstra 
3 
1 2 1 3 1 
2 3 1 
3 1 1 

performing bfs 
All nodes painted white 
Segmentation fault 

을 : 그리고 다음이

g++ -Wall -o dijkstra dijkstra.cpp 
+2

이 디버거를 사용하여 스택 추적을 실행하지 것처럼 loooks. per as : http://stackoverflow.com/questions/3911814/c-in-g-segmentation-fault-when-not-using-pointers/3911873#3911873 – nsanders

+0

대기열 컨테이너를 만드는 segfault가있는 경우 힙이 손상되었습니다. 인접 목록을 만드는 것에 대한 의견이 있지만 문제가있는 곳일 수 있습니다. 노드 배열을 할당하고 있지만 개별 노드도 할당하고 있습니까? –

+1

스타일에 대한 주석 : 변수 이름 "l"(소문자 L)을 사용하면 혼란이 생길 ​​수 있습니다 (왜냐하면 모두가 "1"(1 번)이라고 가정하기 때문입니다). 제발 부탁하고 다른 이름을 사용하십시오. –

답변

0
list<Node*> bfs(... 

당신은 반환 상태 :

return l; 

또한, 여기에 참조 할 필요 : 당신이 지적 곳

Node** &nodes 

그리고는 segfault가 발생하지 않았다. I/O를 버퍼는 그것 때문에 fulshed되지 않은 그것은이

cout << "initialised a queue" << endl; 
list<Node*> l; 
cout << "initialised a list" << endl; 

+1

OP는 "1"(숫자 1)이 아닌 "l"(소문자 L)이라는 지역 변수를 선언했습니다. –

+0

노드를 흰색으로 그릴 때 루프 카운터에 문제가있었습니다. 0에서 시작했지만 이름이 0 인 노드가 없습니다! 1로 초기화하면 문제가 해결됩니다. –

관련 문제