程序打印文件内容无法运行,returns"Instruction at <address> referenced memory at <address>"错误

Program to print file contents unable to run, returns "Instruction at <address> referenced memory at <address>" error

我正在看书学C语言。 我已经读到书中关于文件和命令行参数的部分,但现在我被困在了这段代码的部分:

#include <stdio.h>
int main (int argc,char **argv)
{
    FILE *f=fopen(argv[1],"r");
    int c;
    do
    {
        c=fgetc(f);
        printf("%c",c);
    }
    while(!feof(f));
}

当我运行这个(参数是代码自己的测试文件名)时,出现error message:

The instruction at 0x0000000000401474 referenced memory at 0x0000000000000006. The memory could not be read. Click on OK to terminate the program. Click on CANCEL to debug the program.

这个错误是什么意思,如何解决?

您需要检查文件指针是否不为 NULL,例如

if (f == NULL) {
    return EXIT_FAILURE;
}

此外,文件在使用完毕后需要关闭。

fclose(f);