获取分段错误。 Valgrind 上大小为 1 的无效内存写入(CS50 PSET5 Speller)
Getting segmentation fault. Invalid memory write of size 1 on Valgrind (CS50 PSET5 Speller)
似乎无法让 Valgrind 开心。
Valgrind 结果:
==21003== 大小 1 的无效写入
==21003== 位于 0x4C32E0D:strcpy(在 /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so 中)
==21003== by 0x40125E: load (dictionary.c:111)
==21003== by 0x400964: main (speller.c:40)
大小 8 的无效写入
==22741== 在 0x40123E:加载(dictionary.c:107)
==22741== by 0x400964: main (speller.c:40)
==22741== 地址 0x55cd9a0 是 arena "client"
中大小为 4,183,584 的未分配块之前的 32 字节
问题似乎出在第 110 行,即我的 bool LOAD 中的 StrCpy。
代码如下 - 我不明白为什么大小为 1 的写入无效。
另一个是
n -> 下一个 = table[hashInt];
我不明白为什么我的写入无效。
bool load(const char *dictionary)
{
FILE *file = fopen(dictionary, "r");
if (file == NULL)
{
printf("error opening file");
return 1;
}
char word [LENGTH + 1];
while (fscanf(file, "%s\n", word) != EOF)
{
int hashInt = hash(word);
node *n = malloc(sizeof(n));
if (n == NULL)
{
unload();
return 1;
}
if (table[hashInt] == NULL)
{
table[hashInt] = n;
}
else
{
n -> next = table[hashInt];
table[hashInt] = n;
}
strcpy(n -> word, word);
wordLoaded++;
}
fclose(file);
return 0;
}
这个node *n = malloc(sizeof(n));
可能是一个错字。您是说 sizeof(node)
吗?
似乎无法让 Valgrind 开心。
Valgrind 结果:
==21003== 大小 1 的无效写入 ==21003== 位于 0x4C32E0D:strcpy(在 /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so 中) ==21003== by 0x40125E: load (dictionary.c:111) ==21003== by 0x400964: main (speller.c:40)
大小 8 的无效写入 ==22741== 在 0x40123E:加载(dictionary.c:107) ==22741== by 0x400964: main (speller.c:40) ==22741== 地址 0x55cd9a0 是 arena "client"
中大小为 4,183,584 的未分配块之前的 32 字节问题似乎出在第 110 行,即我的 bool LOAD 中的 StrCpy。 代码如下 - 我不明白为什么大小为 1 的写入无效。
另一个是 n -> 下一个 = table[hashInt];
我不明白为什么我的写入无效。
bool load(const char *dictionary)
{
FILE *file = fopen(dictionary, "r");
if (file == NULL)
{
printf("error opening file");
return 1;
}
char word [LENGTH + 1];
while (fscanf(file, "%s\n", word) != EOF)
{
int hashInt = hash(word);
node *n = malloc(sizeof(n));
if (n == NULL)
{
unload();
return 1;
}
if (table[hashInt] == NULL)
{
table[hashInt] = n;
}
else
{
n -> next = table[hashInt];
table[hashInt] = n;
}
strcpy(n -> word, word);
wordLoaded++;
}
fclose(file);
return 0;
}
这个node *n = malloc(sizeof(n));
可能是一个错字。您是说 sizeof(node)
吗?