搜索功能使程序崩溃

search function causes program to crash

本文关键字:崩溃 程序 功能 搜索      更新时间:2023-10-16

我一直在进行调试器,但似乎无法准确指出出了什么问题。我得出自己的结论,我必须在某个地方缺少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是值得怀疑的。(