【问题标题】:Seg Fault while reading from a file in C从 C 中的文件读取时出现段错误
【发布时间】:2013-02-06 20:49:10
【问题描述】:

我只是想用 3 个命令行参数运行这个程序:2 个整数和 1 个文件名。

我一直在运行我的程序:

a.out 1 2 devices.txt

devices.txt 如下所示:

1

我的主要方法如下所示:

int main(int argc, char* argv[]){
int MaxIterations, T, numDevices;
FILE *devices;

printf("Num arguments: %d \n", argc);
if(argc < 3 || argc > 4){
    printf("ERROR, need exactly 2 or 3 arguments!\n");
    return 1;
} else if (argc == 3){

    MaxIterations = argv[1]; // max iterations allowed
    T = argv[2]; // time interval
    devices = fopen("devices.in", "r");
} else {


    MaxIterations = argv[1];
    T = argv[1];
    devices = fopen(argv[3], "r");
    if(devices == NULL){
        fprintf(stderr, "CANT OPEN FILE: %s!\n", argv[3]);
        exit(1);
    }


}

FILE* file = fopen ("devices.txt", "r");
 int i = 0;

fscanf(devices, "%d", numDevices);
printf("Number of devices: %d \n", numDevices);

fclose(devices);
return 0;

}

我做错了什么导致我出现段错误? 我添加了调试 printf 来确定段错误实际触发的位置,它看起来像它在:

fscanf(devices, "%d", numDevices);

【问题讨论】:

    标签: c file segmentation-fault fault


    【解决方案1】:

    启用编译器警告:

    这是无效的:

    fscanf(devices, "%d", numDevices);
    

    这是你想要的:

    fscanf(devices, "%d", &numDevices);
    

    d 转换说明符需要一个指向有符号整数的指针。您正在传递(未初始化的)对象numDevices 的值。

    【讨论】:

    • 非常感谢!我假设因为我将 numDevices 初始化为 FILE* ,所以我可以直接传递它(因为它已经是一个指针)。
    【解决方案2】:

    问题是 fscanf 函数需要一个指向变量的指针,用于存储从文件中读取的值。你需要类似的东西

    fscanf(devices, "%d", &numDevices);
    

    您收到段错误的原因是,在您的原始代码中,numDevices 的(未初始化的)值被用作要写入的地址 - 由于它不太可能是有效的可写地址,因此段错误是计算机说“不!”的常用方式:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-04
      • 2020-08-14
      • 2019-03-27
      • 1970-01-01
      • 1970-01-01
      • 2018-10-30
      • 2019-06-08
      相关资源
      最近更新 更多