问题描述
我需要创建一个函数来创建一个带有链接方法的哈希表,发生此错误后,我现在继续执行下一个任务,并且在执行循环以从文本文件中读取行时,经过 2 或 3 次迭代后我得到错误“检测到严重错误 c0000374”我找不到任何原因,我搜索了网络当然没有找到问题所在 这是我的代码:
int parseWordsToTable(char* filePath,HashTable* ht) {
FILE* Dictionary = fopen(filePath,"r");
for (int Line = 0; Line < 50; Line++) {
char* line = (char*)malloc(sizeof(char));
if (line == NULL)
exit("Not Enough Memory!");
fgets(line,15,Dictionary);
printf("%s",line);
}
return 1;
}
有时会进行 2 次迭代,有时会进行 3 次,我就是不明白... 断点和错误发生在这一行:
char* line = (char*)malloc(sizeof(char));
顺便说一句,这段代码也是如此:
HashTable* initTable(int tableSize,int hashFunction) {
HashTable* Table = (HashTable*)malloc(sizeof(HashTable));
if (Table == NULL)
exit("Not Enough Memory!");
Table->tableSize = tableSize;
Table->cellsTaken = 0;
Table->hashFunction = hashFunction;
Table->numOfElements = 0;
for (int index = 0; index < tableSize; index++) {
Table[index].hashTable = (HashTableElement*)malloc(sizeof(HashTableElement));
if (Table[index].hashTable == NULL)
exit("Not Enough Memory!");
Table[index].hashTable->key = index;
Table[index].hashTable->chain = (LinkedList*)malloc(sizeof(LinkedList));
if (Table[index].hashTable->chain == NULL)
exit("Not Enough Memory!");
Table[index].hashTable->key = 0;
Table[index].hashTable->chain = NULL;
}
return Table;
}
但仅限于第四次迭代..
解决方法
您必须分配足够的元素。为 fgets()
撒谎是不好的,因为 15 字节的缓冲区被传递,而缓冲区实际上只有一个字节。
另外不要忘记检查 fopen()
是否成功并关闭打开的文件。
int parseWordsToTable(char* filePath,HashTable* ht) {
FILE* Dictionary = fopen(filePath,"r");
if (Dictionary == NULL) return 0; /* check if fopen() is successful */
for (int Line = 0; Line < 50; Line++) {
char* line = (char*)malloc(15); /* allocate enough elements */
if (line == NULL)
exit("Not Enough Memory!");
fgets(line,15,Dictionary);
printf("%s",line);
}
fclose(Dictionary); /* close opened file */
return 1;
}
,
问题是现在为行中的单词分配足够的内存 Hast 表内存分配也是如此 你们的回答真的很快!谢谢!