0

I have implemented a binary tree and its BFS traversal. The program is below:

struct elemq{
    int ele;
    struct elemq *left;
    struct elemq *right;
};

struct que{
    struct elemq *ss;
    struct que *next;
}; 

void qinsert(struct elemq *ptr){
    struct que *node;
    node = (struct que *)malloc(sizeof(struct que));
    if(front == NULL && rear == NULL){
            node->ss = ptr;
            node->next = NULL;
            front = node;
            rear = node;
    }
    else{
            node->ss = ptr;
            node->next = NULL;
            rear->next = node;
            rear = node;
    }
}

struct elemq *qdelete(){
    if(front == NULL && rear == NULL){
            cout << "No elements to delete\n";
            exit(0);
    }
    struct elemq *dd = front->ss;
    struct que *ddd = front;
    front = front->next;
    free(ddd);
return dd;
}

int isempty(){
    if(front == NULL && rear == NULL){
            return 1;
    }
    else{
            return 0;
    }
}

void bfs(){
    qinsert(root);
    struct elemq *fff;
    while(!isempty()){
            fff = qdelete();
            cout << fff->ele  << "\n";
            if(fff->left != NULL){
                    qinsert(fff->left);
            }
            if(fff->right != NULL){
                    qinsert(fff->right);
            }
    }
}  

Though the code is long, it is very simple to understand. elemq structure is the structure of a node in a tree. que is the queue i am using to implement bfs. q insert is to insert element into queue and qdelete deletes the element in the queue. isempty() is for checking if queue is empty or not. The program displays root element and then gives segmentation fault. Please help. struggling from quite some time.

Justin Carrey
  • 3,563
  • 8
  • 32
  • 45

1 Answers1

3

The qdelete function doesn't work correctly if there is only one element in the queue:

struct elemq *qdelete(){
    if(front == NULL && rear == NULL){
            cout << "No elements to delete\n";
            exit(0);
    }
    struct elemq *dd = front->ss;
    struct que *ddd = front;
    front = front->next;
    free(ddd);
return dd;
}

In that case front is set to NULL, but rear still points to the now freed memory.

Add an

if (front == rear) {
    struct elemq *dd = front->ss;
    free(front);
    front = rear = NULL;
} else {
   // what you have
}

to fix it.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431