微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决从文件中读取行的函数,经过几次迭代后会引发错误

我需要创建一个函数来创建一个带有链接方法的哈希表,发生此错误后,我现在继续执行下一个任务,并且在执行循环以从文本文件中读取行时,经过 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 表内存分配也是如此 你们的回答真的很快!谢谢!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。