【问题标题】:Segmentation Fault on fscanf loop in c, CS50 Speller codec 中 fscanf 循环的分段错误,CS50 拼写代码
【发布时间】:2021-07-31 11:37:41
【问题描述】:

我正在解决 cs50 拼写问题,似乎一切正常,除了当我运行 Valgrind 时它说存在分段错误,当我尝试运行代码时也会出现同样的错误。 这是cs50的一个练习,我有一个函数,它接受一个“字典”文件,该文件通过循环逐字读取并存储在哈希表中,以读取每个单词,我使用了一个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;
}

【问题讨论】:

  • 什么是struct node?请创建一个minimal reproducible example
  • 这个函数是否出现segfault?在哪里?哪一行代码?你是在调试器中运行的吗? table 是否使用所有 NULL 显式初始化? wordstruct node 成员是 char 数组还是指针?显示您的hash 函数和table 的定义。
  • OT:关于:printf("Not enough memory or not found %s \n", dictionary); 和类似声明:这不是 fopen() 声明失败的“必然”原因。强烈建议调用:perror( ),它将向stderr 输出您的错误消息和系统认为是错误原因的文本原因。
  • 请发minimal reproducible example,以便我们重现错误并帮助您调试。
  • 关于:while( fscanf(dictionaryPointer, "%s", words) != EOF) 使用 %s 输入格式转换说明符时,始终使用比输入缓冲区长度小 1 的 MAX_width 修饰符,因为此说明符始终将 NUL 字节附加到输入。这也避免了缓冲区溢出的任何可能性(以及由此产生的未定义行为)

标签: c pointers segmentation-fault scanf cs50


【解决方案1】:

看起来您的哈希函数正在返回一个超出范围的索引。 table[hashValue] 如果hashvalue 大于表的大小,则会出现段错误。

如果您将散列函数中的 return 语句更改为 return hashvalue % N; 之类的内容,其中 N 是项目表的数量,那么应该可以解决它。

【讨论】:

    猜你喜欢
    • 2020-08-25
    • 2020-08-08
    • 2020-12-20
    • 2020-10-30
    • 1970-01-01
    • 2011-05-25
    • 2017-03-29
    • 2015-02-09
    • 2022-01-24
    相关资源
    最近更新 更多