【问题标题】:Segmentation fault (core dumped) when using fscanf to read into a pointer使用 fscanf 读入指针时出现分段错误(核心转储)
【发布时间】:2014-05-17 09:40:34
【问题描述】:

我正在尝试使用 fscanf 读取和打印屏幕上的每个字符,但是当我运行程序时出现分段错误(核心转储)。这是我的代码:

#include <stdio.h>

main(int argc, char * argv[]) {
    int *a ;
    FILE *input;

    if (argc>=2) {
        input= fopen(argv[1],"r");

        if (input!=NULL) {
            while (feof(input)==0) {
                fscanf(input,"%d\n",a);
                printf("%d\n",*a);
            }
            fclose(input);
        } else {
            printf("Error!\n");
        }
    }
}

我将文件作为参数提供,如下所示:

./myprog input.txt

文件input.txt 包含以下内容:

23
47
55
70

【问题讨论】:

    标签: c segmentation-fault scanf argv coredump


    【解决方案1】:

    变量a 未初始化为指向有效的内存地址。

    因此,它很可能指向了一个无效的内存地址。

    这是一种解决方法:

    int *a = malloc(sizeof(int));
    ...
    free(a); // when done using it
    

    这是另一种解决方法:

    int b;
    int *a = &b;
    

    但我建议您按照以下步骤操作,以使其更简单、更清洁...


    改变这个:

    int *a;
    

    至此:

    int a;
    

    还有这个:

    fscanf(input,"%d\n",a);
    

    至此:

    fscanf(input,"%d\n",&a);
    

    【讨论】:

      【解决方案2】:

      当你写作时:

      int *a;
      

      那么a 是一个指针,但目前它没有指向任何地方。

      在将其提供给fscanf 之前,您必须使其指向int 的有效存储空间。

      比如main()里面:

      int b;
      a = &b;
      fscanf(input,"%d\n",a);
      

      另外,你的循环是错误的。使用feof 几乎总是一个错误(更不用说,作为循环条件)。相反,您应该测试实际的读取操作。在你的情况下:

      while ( 1 == fscanf(input,"%d\n",a) )
      {
           printf("%d\n", a);
      }
      

      【讨论】:

      • 第一句评论为假。使用int *a; 声明的变量如果是static 变量,则初始化为空指针,例如在模块的全局范围内(即在任何函数之外)定义的变量。然而,在这里讨论的情况下,变量是在main() 函数中声明的,所以它是一个自动变量,不需要初始化。因此它指向任何地方,很可能指向一些不存在或至少不可访问的内存区域,因此读取指向的区域会导致分段异常。
      • 对不起,我一定是看错了 OP 的代码,我以为 int *a;main() 之前。
      猜你喜欢
      • 1970-01-01
      • 2021-05-04
      • 2015-05-12
      • 2016-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-24
      • 1970-01-01
      相关资源
      最近更新 更多