【发布时间】:2017-04-20 19:22:50
【问题描述】:
我一直在调试调试器,但似乎无法准确指出出了什么问题。我得出了自己的结论,我一定是在某处或某处遗漏了 nullptr 检查。如果有人可以提供一些帮助,将不胜感激。
来自调试器的错误消息
这看起来会让程序在这一行崩溃:
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 = '\0') {
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;
}
【问题讨论】:
-
按“Break”并检查调试器中的变量。
-
在您的递归中,null 几乎肯定会以
node的形式传递。您的结构布局表明children位于基数+4,而实际错误来自尝试读取位置0x00000004。调试器在node->children[...]上中断。因此,您可以评估在某处遗漏空检查。 -
不确定这是否是问题所在,但在递归调用
search(word, node->children_[index], index++)中,node->children_[index]和index++的评估顺序未指定。传递index并在之后增加,如果这就是你的意思。 -
@molbdnilo 我几乎会认为这是问题所在。
-
@ molbdnilo 我使用了您的建议并在该参数之外增加了索引。当我这样做时不会发生崩溃,但索引的返回值为 0,而它应该是 15
标签: c++ debugging pointers tree logic