c - 为什么这个 fscanf() 在使用大文件时会出现段错误?

标签 c file linked-list eof scanf

我有一个接收文件名作为参数的函数。 这个想法是读取给定文件中的每个单词并将每个单词保存在链表中(作为具有值和指向下一个结构的指针的结构)。 我可以让它为小文件工作,但是当我提供一个大的 .txt 文件时,我会遇到段错误。 使用 gdb 我可以发现这发生在 while(fscanf(fi, "%s", value) != EOF){ 行。 出于某种原因,当文件较大时,fscanf() 会出现段错误。 因为我可以找出链表部分,所以我在这里粘贴了足够的代码来编译并让你看到我的问题。

所以我的问题是: 为什么 fscanf() 对大 .txt 文件(数千个单词)进行段错误,而不对小文件(十个单词)进行段错误?

顺便问一下,有没有更好的方法来检查文件的结尾?

提前致谢。

bool read(const char* file){
    // open file
    FILE* fi = fopen(file, "r"); //file is a variable that contains the name of the file to be opened
    if (fi == NULL)
    {
        return false;
    }

    // malloc for value
    char* value = malloc(sizeof(int));

    // fscanf() until the end of the file
    while(fscanf(fi, "%s", value) != EOF){ // HERE IS MY PROBLEM
        // some code for the linked list
        // where the value will be saved at the linked list
    }

    // free space
    free(value);

    // close the file
    fclose(fi);

    return true;
}

最佳答案

不,这是你的问题:

 char* value = malloc(sizeof(int));   //  <<<<<<< You allocate only place for an int 

 while(fscanf(fi, "%s", value) != EOF){ // <<<<<<< but you read a huge string 

所以你最终会遇到缓冲区溢出!

您必须通过设置一些限制来确保您永远不会溢出缓冲区的大小。例如,使用 fscanf() 的宽度字段指示要为字符串读取的字符的最大大小:

 char* value = malloc(512);   // Allocate your buffer 
 while(fscanf(fi, "%511s", value) != EOF){ // read max 511 chars + 1 char for terminating 0  
    ...

关于c - 为什么这个 fscanf() 在使用大文件时会出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27390573/

相关文章:

c - *在实践中* : decent C code, 或体面的手写汇编程序哪个更快?

c - 为什么 C 不提供结构比较?

c - 此行有多个标记 - 语法错误 (eclipse)

C++链表isEmpty函数

c - 获取链接列表fgets和scanf C的输入

java - C# 和 Java 中是否有 C 方法 _strtod_l 的等效项?

java - 当我复制两个空路径时会发生什么并且为什么它不抛出异常?

file - 强制下载 'data:text/plain' URL

linux - append 到文件时如何避免竞争条件?

java - 在链表中搜索对象变量