在g++上执行二进制搜索树进入无限循环
Execution of binary search tree on g++ goes into infinite loop
我编写了这个BST来计算给定文件中每个单词的数量。该文件每行都有重复的单词。
/*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);
}
}
我的查询是:1.在main()
中,我将node
初始化为NULL
,并且我使用相同的指针来调用trees
方法。程序不应该崩溃吗?既然我正在取消引用NULL
指针?
2:当我在g++编译器(gcc 4.6.3)上运行这段代码时,程序在_word == newNode->m_word
时交给createTree()
方法,不会返回。在else if ( _word == newNode->m_word )
条件下似乎存在一个无限循环。
但在VisualStudio2008上执行相同的代码并没有问题,我能够得到正确的答案
你知道查询1和2吗?
根据实现(我的是MSVC++),只有当您实际访问不存在对象的任何成员时,它才可能导致分段错误。由于createTree
不接触任何东西,它的工作方式几乎像一个静态函数,不会导致分割故障。
也许你应该让它成为static
,比现在的方式更有意义。
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 正在尝试重载二进制搜索树分配运算符
- 过载'operator new'如何导致无限循环?
- 使用C++创建特殊的二叉搜索树
- C++正则表达式无限循环
- 程序在尝试猜测它选择的随机数时进入无限循环?
- 在递归二叉搜索树中搜索
- 遍历链表时的无限循环
- 循环链表:无限循环
- 比较两个字符串后卡在无限循环中
- 在二叉搜索树中插入时出现分段错误
- 在做一段时间内检查字符的无限循环
- 运行无限循环的最小二叉树问题
- 广度优先搜索陷入无限循环
- 如何修复关卡顺序遍历问题(二叉树)的无限循环错误
- 二叉搜索陷入无限循环
- C++中的二进制搜索函数返回无限循环
- 在g++上执行二进制搜索树进入无限循环
- 最小堆通过二叉树的数组表示;MoveDown函数无限循环
- 二叉搜索树的复制构造函数被无限调用