I was practicing the code of BFS of tree with STL in c++ and I got one runtime error that i can't debug.everything is working fine if i dont call the printout() function
. Please help as I am new to STL..
#include<iostream>
#include<malloc.h> //on llvm we don't need this
#include<list>
using namespace std;
typedef struct Node{
int val;
struct Node* left;
struct Node* right;
}node;
void push(node** root,int val)
{
if(!(*root))
{
node* temp=(node*)malloc(sizeof(node));
temp->val=val;
temp->right=temp->left=NULL;
*root=temp;
}
else if(val<(*root)->val)
push(&((*root)->left),val);
else
push(&((*root)->right),val);
}
void printout(node* head)
{
node* temp;
temp=head;
list<node*>qu;
//using bfs here
while(temp!=NULL)
{
cout<<temp->val<<endl;
if(temp->left!=NULL)
qu.push_back(temp->left);
if(temp->right!=NULL)
qu.push_back(temp->right);
temp=qu.front();
qu.pop_front();
//free(temp);
}
}
int main()
{
node* root=NULL;
push(&root,3);
push(&root,4);
push(&root,1);
push(&root,10);
push(&root,2);
printout(root);
}
though it is printing corrent output but with runtime time
3
1
4
2
10
a.out(613) malloc: *** error for object 0x7fff55ed8bc8: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
You are calling qu.front()
in each iteration without checking if qu
is empty. If it is empty - and finally it will be - your code breaks.
The simplest solution would be to check if qu
is empty:
if (qu.empty()) {
temp = NULL;
} else {
temp=qu.front();
qu.pop_front();
//free(temp);
}
However, that looks weird. I would change the loop completely and use !qu.empty()
as condition for the while
loop.
list<node*> qu;
qu.push_back(head);
while(!qu.empty()) {
node* temp = qu.front();
qu.pop_front();
if(temp->left)
qu.push_back(temp->left);
if(temp->right)
qu.push_back(temp->right);
//free(temp);
}
What happens is that when you get to the final "leaf" in the tree, the temp->left
and temp->right
are both NULL
and you get an empty qu list. Calling qu.front()
causes undefined behavior on an empty list: http://en.cppreference.com/w/cpp/container/list/front
You could add a size check before calling front.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.