Monday, 26 August 2013

Execution of binary search tree on g++ goes into infinite loop

Execution of binary search tree on g++ goes into infinite loop

I have written this BST to count the number of each words in a given file.
The file has repeated words in every line.
/*all necessary headers*/
class tree
{
public:
tree(string _word) : left( NULL ), right ( NULL ), m_word(_word),
count(1) {}
tree* createTree(tree *newNode, string _word)
{
if( newNode == NULL )
newNode = new tree(_word);
else if( _word == newNode->m_word)
newNode->count++;
else if( _word m_word)
newNode->left = createTree(newNode->left,_word);
else
newNode->right = createTree(newNode->right,_word);
return newNode;
}
private:
string m_word;
int count;
tree *left;
tree *right;
};
int main()
{
string csword;
tree *node = NULL;
ifstream str("word.txt");
while( !str.eof())
{
str>>csword;
node = node->createTree(node,csword);
}
}
My queries are : 1. In main() i am initializing the node to NULL, and I am
using the same pointer to call the trees methods. Shouldn't the program
crash? Since i am de-referencing a NULL pointer?
2 : when I run this piece of code on a g++ compiler( gcc 4.6.3 ), the
program hands in the createTree() method when _word == newNode->m_word and
does not come back. There seems to be an infinite loop going on in the
else if ( _word == newNode->m_word ) condition.
But executing the same code on Visual Studio 2008 has no issues and i am
able to get correct answer.
Any idea about the query 1 and 2 ?

No comments:

Post a Comment