CS50 pset5 Speller

问题描述 投票:0回答:1

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

这是我的load();

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;
}

和check();

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;
}
cs50
1个回答
0
投票

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

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

由于table是列表的开头,所以不需要分配检查节点。如果checker是初始化为table[bucket]的节点指针,则程序将对列表进行爬网,并且(应该)仅访问分配的内存。

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

© www.soinside.com 2019 - 2024. All rights reserved.