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
이 디버거를 사용하여 스택 추적을 실행하지 것처럼 loooks. per as : http://stackoverflow.com/questions/3911814/c-in-g-segmentation-fault-when-not-using-pointers/3911873#3911873 – nsanders
대기열 컨테이너를 만드는 segfault가있는 경우 힙이 손상되었습니다. 인접 목록을 만드는 것에 대한 의견이 있지만 문제가있는 곳일 수 있습니다. 노드 배열을 할당하고 있지만 개별 노드도 할당하고 있습니까? –
스타일에 대한 주석 : 변수 이름 "l"(소문자 L)을 사용하면 혼란이 생길 수 있습니다 (왜냐하면 모두가 "1"(1 번)이라고 가정하기 때문입니다). 제발 부탁하고 다른 이름을 사용하십시오. –