搜索功能使程序崩溃
search function causes program to crash
我一直在进行调试器,但似乎无法准确指出出了什么问题。我得出自己的结论,我必须在某个地方缺少nullptr检查。如果有人能提供一些帮助,将不胜感激。
debugger的错误消息
错误msg
看起来使程序在此行上崩溃:
if (node->children_[index] == nullptr) {
搜索功能
Node* search(const string& word, Node* node, int index) const {
Node* temp;
//same as recurssive lookup just difference is returns node weather terminal or not
if (index < word.length()) {
index = node->getIndex(word[index]);
if (node->children_[index] == nullptr) {
return nullptr;
}
else {
temp = search(word, node->children_[index], index++);
}
}
return temp; // this would give you ending node of partialWord
}
节点结构用于参考
struct Node {
bool isTerminal_;
char ch_;
Node* children_[26];
Node(char c = ' ') {
isTerminal_ = false;
ch_ = c;
for (int i = 0; i < 26; i++) {
children_[i] = nullptr;
}
}
//given lower case alphabetic charachters ch, returns
//the associated index 'a' --> 0, 'b' --> 1...'z' --> 25
int getIndex(char ch) {
return ch - 'a';
}
};
Node* root_;
int suggest(const string& partialWord, string suggestions[]) const {
Node* temp;
temp = search(partialWord, root_, 0);
int count = 0;
suggest(partialWord, temp, suggestions, count);
return count;
}
可能是一件非常简单的事情。如果不挖掘,我不确定->
操作员与==
操作员的等级。我会花一秒钟,然后尝试在这样的" node->children_[index] == nullptr
"部分周围放括号:
(node->children_[index]) == nullptr
只是为了确保逻辑看起来像您的意图一样运行。
dr t
我相信根本原因是您将index
用于两个不同的目的:作为您要寻找的单词的索引,以及作为节点子女的索引。br>当您到达递归时,index
已更改含义,并且从那里都下坡了。
您也将index++
传递给递归,但是index++
的值是它在增量之前的值。
您应该通过index + 1
。
[不同程序中的问题是,函数参数的评估顺序未指定,并且您绝不应该修改变量并将其在同一参数列表中使用。(我甚至要说您绝不应该在参数列表中修改,但许多人都不同意。(
但是您根本不应该在这里使用相同的变量,所以...]
我会亲自重组代码,类似的内容:
Node* search(const string& word, Node* node, int index) const {
// Return immediately on failure.
if (index >= word.length())
{
return nullptr;
}
int child_index = node->getIndex(word[index]);
// The two interesting cases: we either have this child or we don't.
if (node->children_[child_index] == nullptr) {
return nullptr;
}
else {
return search(word, node->children_[child_index], index + 1);
}
}
(旁注:从const
函数返回指针到非CONST内部Node
是值得怀疑的。(
相关文章:
- 提升 ASIO Async_receive崩溃程序
- 类指针方法崩溃程序
- get_body来自 IHTMLDocument2 崩溃程序
- 是否有可能存在不会崩溃程序的内存问题
- 调试运行时出现奇怪的崩溃程序(Eclipse C++)
- 儿童对话框 - setWindowTexta或sendmessagea崩溃程序-MFC
- 顶点阵列GLFW崩溃C 程序
- 将值分配给Float数据类型崩溃程序
- OpenCV-将变量添加到类成员崩溃程序
- boost::interprocess::managed_shared_memory 崩溃程序
- 将枚举值分配给整数崩溃程序
- SDL 1.2 -> SDL 2.0(崩溃程序)
- 空析构函数崩溃程序:C++
- 冒泡排序崩溃程序c++
- Ofstream关闭崩溃程序
- 删除字符* 崩溃程序
- c++矢量擦除崩溃程序
- Lua_getglobal崩溃程序
- 通过Copy Constructor创建的e2打印崩溃程序
- RNG崩溃c++程序