c 中 fscanf 循环的分段错误,CS50 Speller 代码
Segmentation Fault on fscanf loop in c, CS50 Speller code
我正在解决 cs50 拼写器问题,似乎一切正常,除了当我 运行 Valgrind 时它说存在分段错误,当我尝试 运行ning 代码时出现相同的错误也发生。
这是 cs50 的一个练习,我有一个函数,它接受一个“字典”文件,该文件通过循环逐字读取并存储在哈希表中,以读取每个单词,我使用 while 循环使用 fscanf 从中获取字符串字典的指针,指向一个名为 words 的字符串(它比字典中的任何单词都大),循环保持 运行ning 直到到达 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;
}
看起来您的散列函数正在 returning 一个越界的索引。 table[hashValue]
如果 hashvalue
大于 table 的大小,那么这将出现段错误。
如果您将散列函数中的 return 语句更改为类似 return hashvalue % N;
的内容,其中 N 是项目的数量 table,应该可以修复它。
我正在解决 cs50 拼写器问题,似乎一切正常,除了当我 运行 Valgrind 时它说存在分段错误,当我尝试 运行ning 代码时出现相同的错误也发生。 这是 cs50 的一个练习,我有一个函数,它接受一个“字典”文件,该文件通过循环逐字读取并存储在哈希表中,以读取每个单词,我使用 while 循环使用 fscanf 从中获取字符串字典的指针,指向一个名为 words 的字符串(它比字典中的任何单词都大),循环保持 运行ning 直到到达 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;
}
看起来您的散列函数正在 returning 一个越界的索引。 table[hashValue]
如果 hashvalue
大于 table 的大小,那么这将出现段错误。
如果您将散列函数中的 return 语句更改为类似 return hashvalue % N;
的内容,其中 N 是项目的数量 table,应该可以修复它。