0

I was trying to implement BFS on my own and wrote some code for it. I ran the code through debugger and all iterations of the while loop ran fine except the last one. When the last pointer is inside the queue (buffer) , the if condition :

    if (l) {
        buffer.push(l);
        cout << l - > val << endl;
    }

becomes true (when it should be false). And it leads to segmentation fault. Why is this happening? Here is the full code...

#include <iostream>

#include <vector>

#include <queue>

using namespace std;

struct node {
    int val;
    struct node * left;
    struct node * right;
};

vector < int > a {
1,
5,
4,
3,
7,
2,
9
};

vector < node > tree(6, {
0,
nullptr,
nullptr
});

void make_tree() {
    for (auto i = 0; i < 7; i++) {
        tree[i].val = a[i];
    }

    for (auto j = 0; j < 3; j++) {
        tree[j].left = & (tree[2 * (j + 1) - 1]);
        tree[j].right = & (tree[2 * (j + 1)]);
    }

}
node * temp = & tree[0];
queue < node * > buffer;

void BFS() 
{

    buffer.push(temp);

    node * r = nullptr;

    node * l = nullptr;

    cout << (buffer.front()) - > val << endl;

    while (!buffer.empty()) 
    {

        l = (buffer.front() - > left);
        if (l) {
            buffer.push(l);
            cout << l - > val << endl;
        }

        r = (buffer.front() - > right);
        if (r) {
            buffer.push(r);
            cout << r - > val << endl;
        }
        buffer.pop();

      }

}

int main() 
{

make_tree();
BFS();

return 0;

}
  • Please turn on compiler warnings. The code as give cannot compile, because `- >` (two tokens, separated by a space) is not `->` (one token). – Eljay Apr 26 '20 at 14:06
  • Also, you should use `tree.at(i)` instead of `tree[i]`. – Eljay Apr 26 '20 at 14:10
  • Okay I will do that! But the issue is that it is printing all the elements breadth wise just fine , but it gets segmentation fault due to the last iteration of the while loop. – gettingBetterprogrammer Apr 26 '20 at 14:10

1 Answers1

1

You are indexing into tree from 0 .. 6, but are only creating 6 nodes. Creating 7 nodes fixes it:

vector < node > tree(7, { 0, nullptr, nullptr });
cigien
  • 57,834
  • 11
  • 73
  • 112
  • Oh my bad! it solved the segmentation fault . Thanks. Hey but can you run the above code with debugger and tell me why the last iteration makes the if condition true? – gettingBetterprogrammer Apr 26 '20 at 14:16
  • Probably, but I highly recommend learning how to do that yourself. Then you won't even need to ask for help :) – cigien Apr 26 '20 at 14:18