这是我在这里的第一篇文章,我需要帮助。Speller的lalaland.txt输出为958个字,但应为955个字。(3 x“ i'd”)。我曾尝试对“ i”进行硬编码,但是输出为〜850。 (程序拒绝了所有的“我”)。tolstoy.txt-13117,但必须为13008,大多数单词是两个字母(Ha,ha,ga,Ma,Id等)。同时同一单词的其他部分通过检查。与所有其他文本相同的情况。程序无缘无故地传递和拒绝相同的单词。我不知道发生了什么。
这是我的load();
bool load(const char *dictionary)
{
FILE *inputFile = fopen(dictionary, "r");
if (inputFile == NULL)
{
return false;
}
while (true)
{
node *n = malloc(sizeof(node));
if (n == NULL)
{
return 1;
}
n->next = NULL;
int sc = fscanf(inputFile, "%s", n->word);
if (sc == EOF)
{
free(n);
break;
}
int bucket = hash(n->word);
if (table[bucket] == NULL)
{
table[bucket] = n;
}
else
{
n->next = table[bucket]->next;
table[bucket]->next = n;
}
sizeCount++;
}
fclose(inputFile);
return true;
}
和check();
bool check(const char *word)
{
int i = hash(word);
if (table[i] == NULL)
{
return false;
}
struct node *checker = malloc(sizeof(node));
checker = table[i];
while (true)
{
if (strcasecmp(checker->word, word) == 0)
{
return true;
}
if (checker->next == NULL)
{
break;
}
checker = checker->next;
}
free(checker);
return false;
}
请记住,table
是节点指针的数组,而不是节点的数组。因此,没有为next
或word
元素分配内存。负载中的这些行正在访问不属于table [bucket]:
n->next = table[bucket]->next;
table[bucket]->next = n;
由于table
是列表的开头,所以不需要分配检查节点。如果checker
是初始化为table[bucket]
的节点指针,则程序将对列表进行爬网,并且(应该)仅访问分配的内存。
内存冲突导致不可预测的结果。您可以运行valgrind -v
查看完整的报告。