0

the following code crashes at runtime but works perfectly fine if struct node* a[10] is declared globally.Where does the problem lie.Any insight would be appreciated. Thank you!

 #include<bits/stdc++.h>
    using namespace std;
    int rear=-1;
    int front=-1;

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

    struct node *newnode(int d){
        struct node* node1=new node;
        node1->data=d;
        node1->left=NULL;
        node1->right=NULL;
        return(node1);
    }

    void enqueue(struct node* a[],struct node* tempnode){
        rear++;
        a[rear]=tempnode;
    }

    struct node* dequeue(struct node* a[]){
       front++;
      return a[front];
    }

    void bfs(struct node* root,struct node* a[]){
        struct node *tempnode=root;
        while(tempnode){
            cout<<tempnode->data;
            if(tempnode->left)
                enqueue(a,tempnode->left);
            if(tempnode->right)
                enqueue(a,tempnode->right);
            tempnode=dequeue(a);
        }
    }

    main() {
        struct node* a[10];

        struct node* root=newnode(1);
        root->left=newnode(2);
        root->right=newnode(3);
        root->left->left=newnode(-1);
        root->left->right=newnode(0);
        bfs(root,a);
    }

http://www.geeksforgeeks.org/level-order-tree-traversal/

  • 4
    Unrelated to your question, but I suggest you read [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – Some programmer dude Oct 05 '17 at 16:55
  • 2
    `struct node* c=new node; c=a[front];` produces memleak. – Jarod42 Oct 05 '17 at 16:57
  • 1
    `main` seems to be missing the return type (`int`). – user4581301 Oct 05 '17 at 17:07
  • @Jarod42 i can't use delete(c) here.Further i modified the function f=-1; struct node* dequeue(struct node* a[]){ front++; return a[front]; } Yet it crashes again.. – Daksh Sharma Oct 05 '17 at 17:24
  • Count the number of enqueues and the number of dequeues. If you have more dequeues than enqueues... that would be bad and give you a great place to start debugging. – user4581301 Oct 05 '17 at 17:45

2 Answers2

0

Initialize the array "a" -

int main() {
    struct node* a[10] = {NULL};

The problem is not occurring when struct node* a[10] is declared globally because global variables are initialized automatically.

H.S.
  • 11,654
  • 2
  • 15
  • 32
0

You forget to initialize a:

struct node* a[10]{};

so your dequeue will indeed return nullptr once your queue is empty.

Jarod42
  • 203,559
  • 14
  • 181
  • 302