简体   繁体   English

c,CS50 拼写代码中 fscanf 循环的分段错误

[英]Segmentation Fault on fscanf loop in c, CS50 Speller code

I'm doing the cs50 speller problem and it seems everything is working except when I run Valgrind it says there is a segmentation fault, when I try running the code the same error also occurs.我正在处理 cs50 拼写问题,似乎一切正常,除了当我运行 Valgrind 时,它说存在分段错误,当我尝试运行代码时,也会出现同样的错误。 This is an exercise from cs50 where I have a function which takes a "dictionary" file, which is read word by word by a loop and stored in a hashtable, to read each word, I used a while loop using fscanf taking a string from the pointer of the dictionary, to a string called words (which is bigger than any word on the dictionary), the loop keeps running until reaching EOF:这是cs50的一个练习,我有一个function,它采用“字典”文件,通过循环逐字读取并存储在哈希表中,以读取每个单词,我使用了一个while循环,使用fscanf从字典的指针,指向一个叫做单词的字符串(它比字典上的任何单词都大),循环一直运行直到到达 EOF:

//Puts dictionary words into hashtable

bool load(const char *dictionary)
{
    // TODO
    FILE *dictionaryPointer = fopen(dictionary,"r");
    if (dictionaryPointer == NULL)
    {
        printf("Not enough memory or not found %s \n", dictionary);
        return false;
    }
    //LENGTH is 45, the maximum amount of letters in a word.
    char words[LENGTH + 1];
    //Here is the segmentation fault problem
    while( fscanf(dictionaryPointer, "%s", words) != EOF)
    {
        node *n = malloc(sizeof(node));
        if (n == NULL)
        {
            printf("Not enough memory in node. \n");
            return false;
        }
        strcpy(n->word, words);
        int hashValue = hash(n->word);
        n->next = table[hashValue];
        table[hashValue] = n;
        sizeDictionary++;
    }
    fclose(dictionaryPointer);
    return true;
}

Looks like your hash function is returning an index that's out of bounds.看起来您的 hash function 正在返回一个超出范围的索引。 table[hashValue] If hashvalue is greater than the size of table, then this will seg fault. table[hashValue]如果hashvalue大于 table 的大小,那么这将 seg 错误。

If you change the return statement in your hash function to something like return hashvalue % N;如果您将 hash function 中的 return 语句更改为类似return hashvalue % N; where N is the number of items table, that should fix it.其中 N 是项目表的数量,应该修复它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM