Reputation: 205
I'm trying to traverse on a binary tree to find someone's ID by using his/her ID number. When I debug this function it works well, but on the other hand, when I directly run, it terminates itself.. Can someone figure it out please?
struct person{
char ID[15];
char name[30] ;
char surname[30];
person *left;
person *right;
};
struct tree{
person *root;
void bfsSearch();
void BFS(person*,char*);
};
void tree::BFS(person *root,char *search)
//BFS traversal on a binary tree
{
char *temp;
std::deque<person *> q;
q.push_back(root);
temp=strncpy(temp,q.front()->ID,8);
while (q.size() != 0)
{
person *next = q.front();
if (strcmp(search,temp)==0)
{
cout<<"Result: "<<q.front()->ID<<endl;
break;
}
q.pop_front();
if (next->left)
q.push_back(next->sol);
if (next->right)
q.push_back(next->sag);
temp=strncpy(temp,q.front()->ID,8);
}
}
void tree::bfsSearch()
{
person *scan;
char *data,*temp;
data=new char[15];
scan=root;
cout<<"Enter the Person`s ID to search: ";cin>>data;
BFS(root,data);
}
Upvotes: 2
Views: 2771
Reputation: 110108
char *temp;
temp=strncpy(temp,q.front()->ID,8);
You are copying data into an uninitialized pointer, which is undefined behavior. You need to declare temp
as an array, or allocate it dynamically. Since you are only copying up to 8 bytes, using char temp[9];
should be enough. Note though that strncpy
will leave the string unterminated if the input was too long, so you'd need to add temp[8]=0;
to be safe.
There is also no point in assigning the result of strncpy
back to temp
, since it just returns its first argument.
It's much better to do things the C++ way: Use std::string
and avoid all this messing around with char
pointers and null-terminators.
Upvotes: 1