CS50 pset5 拼写器

CS50 pset5 Speller

这是我第一次 post 来这里,我需要帮助。 lalaland.txt 的 Speller 输出是 958 个单词,但应该是 955 个。(3 x "i'd")。 我曾尝试硬编码 "i'd",但输出为 ~850。 (程序拒绝了所有 "i'd")。 tolstoy.txt - 13117,但必须是 13008,大多数单词都是两个字母(Ha、ha、ga、Ma、I'd 等)。 同时同一单词的其他部分通过检查。 与所有其他文本的情况相同。程序无故传递和拒绝相同的词。 我不知道发生了什么。

这是我的负载();

bool load(const char *dictionary)
{
    FILE *inputFile = fopen(dictionary, "r");
    if (inputFile == NULL)
    {
        return false;
    }

    while (true)
    {
        node *n = malloc(sizeof(node));
        if (n == NULL)
        {
            return 1;
        }
        n->next = NULL;
        int sc = fscanf(inputFile, "%s", n->word);
        if (sc == EOF)
        {
            free(n);
            break;
        }

        int bucket = hash(n->word);
        if (table[bucket] == NULL)
        {
            table[bucket] = n;
        }
        else
        {
            n->next = table[bucket]->next;
            table[bucket]->next = n;
        }
        sizeCount++;
    }
    fclose(inputFile);
    return true;
}

并检查();

bool check(const char *word)
{
    int i = hash(word);
    if (table[i] == NULL)
    {
        return false;
    }
    struct node *checker = malloc(sizeof(node));
    checker = table[i];
    while (true)
    {
        if (strcasecmp(checker->word, word) == 0)
        {
            return true;
        }
        if (checker->next == NULL)
        {
            break;
        }
        checker = checker->next;
    }
    free(checker);
    return false;
}

记住,table是节点指针数组,不是节点数组。因此,没有为 nextword 元素分配内存。 load 中的这些行正在访问不属于 table[bucket]:

的内存
n->next = table[bucket]->next;
table[bucket]->next = n;

由于table是链表的头部,所以不需要在check中分配节点。如果 checker 是一个节点指针,初始化为 table[bucket],程序将很好地抓取列表,并且(应该)只访问分配的内存。

内存违规导致了不可预测的table结果。您可以 运行 valgrind -v 查看完整报告。