Note that there are some explanatory texts on larger screens.

plurals
  1. POc++: Getting a segfault when initialising a queue of pointers
    primarykey
    data
    text
    <p>I am trying to implement the BFS algorithm described in CLRS. And have the following:</p> <pre><code>#include &lt;iostream&gt; #include &lt;list&gt; #include &lt;queue&gt; #include &lt;string&gt; #include &lt;sstream&gt; 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&lt;Node*&gt; bfs(Node** &amp;nodes,int numNodes,int startNode) { cout &lt;&lt; "performing BFS\n"; for(int i = 0; i &lt; numNodes;i++) { nodes[i]-&gt;colour = 'w'; nodes[i]-&gt;parent = 0; } cout &lt;&lt; "All nodes painted white" &lt;&lt;endl; queue&lt;Node*&gt; q; // segfault occurs here cout &lt;&lt; "initialised a queue" &lt;&lt; endl; list&lt;Node*&gt; l; cout &lt;&lt; "initialised a list" &lt;&lt; endl; nodes[startNode]-&gt;colour = 'g'; nodes[startNode]-&gt;distance = 0; q.push(nodes[startNode]); Node* u; Node* v; while(!q.empty()){ u = q.front(); for(int i = 0;i &lt; u-&gt;numNbr; i++) { v = nodes[u-&gt;neighbours[i]]; if(v-&gt;colour == 'w'){ v-&gt;colour = 'g'; v-&gt;distance = (u-&gt;distance)+1; v-&gt;parent = u; q.push(v); } } l.push_front(u); u-&gt;colour = 'b'; q.pop(); } return l; } int main(){ int nodeCount; cin &gt;&gt; nodeCount; cin.ignore(); Node** nodes = new Node*[nodeCount+1]; for(int i = 0; i &lt; nodeCount; i++){ .... // build up the nodes in the adjacency list } list&lt;Node*&gt; l = bfs(nodes,nodeCount,1); cout &lt;&lt; "BFS of nodes\n"; for(list&lt;Node*&gt;::iterator it = l.begin();it != l.end();it++){ cout &lt;&lt; (*it)-&gt;name &lt;&lt; " "; } cout &lt;&lt; endl; return 0; } </code></pre> <p>When I run this however, I only get the following output followed by a <code>segfault</code> when the queue is initialised:</p> <pre><code>jonathan@debian:~/Code/cpp/dijkstra$ ./dijkstra 3 1 2 1 3 1 2 3 1 3 1 1 performing bfs All nodes painted white Segmentation fault </code></pre> <p>I am compiling with the following command:</p> <pre><code>g++ -Wall -o dijkstra dijkstra.cpp </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload