I’m a computer science college student. Yesterday, I have a class about Binary Search Tree using C++. We are taught by lab assistants in that class.
They define the node in the tree as a struct like this :
struct Data{
char name[15];
int age;
Data *left,*right;
};
and they give us a code to search within the BST like this:
// temp is current node, name is the value of the node to be searched for.
Data* search(Data *temp,char name[]) {
if(strcmp(temp->name,name)>0)
search(temp->left,name);
else if(strcmp(temp->name,name)<0)
search(temp->right,name);
else
return temp;
}
I notice that code is wrong. If the function gets into the first or the second if block, it will not execute any return statement.
But when the lab assistant run the code, it works just fine.
I thought maybe this behaviour is compiler specific.
But when I tried that code on gcc, the function also work fine. (our university uses microsoft visual c++ compiler)
Can anyone explain what is happening? why is this code working?
PS: ignore other errors such as when the node is empty, the value is not found, etc.
It’s just undefined behavior.
It appears to work because there’s one register that holds the return value. In the deepest paths of the recursion tree, the
tempis moved into that register, and never cleared or changed afterwards, so that register will contain the correct node until the first call returns.When the first call returns, the calling context checks that register for the return value, which happens to be correct. But you shouldn’t rely on this. It’s not safe to assume it will always work.