从文件中读取行的函数,几次迭代后会引发错误

function for reading lines from file, after few iterations raises an error

我需要创建一个使用链式方法创建散列的函数 table,发生此错误后我暂时继续执行下一个任务,并在执行循环以从文本文件中读取行时,之后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个字节的buffer而实际上buffer只有一个字节是不好的。

另外不要忘记检查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 table 内存分配也是如此 你们的回答真快!谢谢!