【发布时间】: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 显式初始化?word的struct 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