有人可以帮我在这里找到段错误吗?

标签 c pointers segmentation-fault trie

编辑:所以,事实证明“索引”没有返回到 0。那么。这修复了一个段错误。但仍然遇到不同的段错误。正在努力。

node* new_node(void){
    node* ptr = malloc(sizeof(node));
    for (int i = 0; i<27; i++) {
        ptr->next[i] = NULL;
    }
    return ptr;
}
bool load(const char* dictionary)
{
    FILE* dict = fopen(dictionary, "r");
    node* ptr = new_node;
    char word[LENGTH+1];
    int index = 0;
    for (int c = fgetc(dict); c!=EOF; c = fgetc(dict)){
        if(c!='\n'){
            word[index]=c;
            index++;
        }
        else {
            for(int x=0; x<=index; x++){
                int ch = (word[x] == '\'') ? 26 : tolower(word[x])-'a';
                if (ptr->next[ch] == NULL){
                    ptr->next[ch] = new_node;
                }
                ptr = ptr->next[ch];
            }
            ptr->end=true;
        }
    }
    return true;
}

我正在尝试为字典实现一个 trie 数据结构,但我的程序似乎在这个函数的某处出现了段错误。即使在 GDB 的帮助下,我似乎也无法确定它,所以有人可以帮助我吗?

节点定义如下:

typedef struct node{
    bool end;
    struct node* next[27];
} node;

字典文件:

a
aaa
aaas
aachen
aalborg
aalesund
aardvark
aardvark's
aardvarks
aardwolf

(...)

最佳答案

您的代码中有很多问题:

  • 当您使用malloc 分配内存时,它是未初始化的。分配后直接初始化它,这样 NULL 指针真的是空的。 (calloc,“malloc”的表亲,将所有内存初始化为零。)

  • 当你遍历单词时,你不应该包含index:

    for (int x = 0; x < index; x++) ...
    
  • 当您找到一个单词的结尾时,您必须将 index 重置为 0。否则,您将追加到旧单词并溢出缓冲区。 (您可能还应该强制执行“索引”的上限。)

  • 同样,当您将单词插入到 trie 中时,您必须将 trie 遍历的指针重置为 trie 的根。这里需要两个指针:一个根节点指针和一个用于遍历 trie 的辅助指针。

  • 照原样,您的 trie 对您的函数而言是本地的。返回根节点,以便其他函数可以使用该 trie,或者在失败时返回 NULL

修复这些问题,您将拥有一个不会崩溃的功能。 (它仍然会泄漏内存并且可能无法正确构建 trie。)

    node *load(const char *dictionary)
    {
        FILE *dict = fopen(dictionary, "r");
        node *head = calloc(1, sizeof(node));

        char word[LENGTH + 1];
        int index = 0;

        for (int c = fgetc(dict); c != EOF; c = fgetc(dict)) {
            if (c != '\n') {
                word[index] = c;
                index++;
            } else {
                node *ptr = head;

                for (int x = 0; x < index; x++) {
                    int ch = (word[x] == '\'') ? 26 : tolower(word[x]) - 'a';
                    if (ptr->next[ch] == NULL) {
                        ptr->next[ch] = calloc(1, sizeof(node));
                    }
                    ptr = ptr->next[ch];
                }
                ptr->end = true;
                index = 0;
            }
        }

        return head;
    }

关于有人可以帮我在这里找到段错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36310496/

相关文章:

Java 找不到用于 native 方法的 .so C 库

c - 尝试从另一个包含结构的函数调用一个函数

string - 将 UnsafeMutablePointer 与 String 或 Character 类型一起使用时出现不一致

C++——空指针

c++ - vector 指针,继承

Python C 扩展嵌套字典段错误

c - 搜索/删除时出现 2-3 棵树分割错误

c - 使用 while 循环的印度算法

c++ - QT painter 仅在关闭窗口时更新计时器更新

c - 段错误 : 11 in C code