分段错误
这是我的代码。
#include<stdio.h>
int main(int argc,char** argv)
{
FILE* fp;
fp=fopen(argv[1],"r");
struct element{
int value;
char activity;
};
typedef struct element element;
element a;
printf("%d",feof(fp));
}
现在,如果我不给出最后一个 printf
命令,它不会给我一个分段错误,但如果我给它 printf
它会给我一个段错误。为什么?
我得到了上一个问题的答案,现在我有另一个问题,
我已将 .txt 附加到我的 makefile 中的输入文件中。现在我有另一个问题。 on 命令 make 它给出错误。
0make: *** [a.out] Error 1
为什么?
Here is my code.
#include<stdio.h>
int main(int argc,char** argv)
{
FILE* fp;
fp=fopen(argv[1],"r");
struct element{
int value;
char activity;
};
typedef struct element element;
element a;
printf("%d",feof(fp));
}
Now if I don't give the last printf
command it does not give me a segmentation fault, but if I give it printf
it gives me a seg fault. Why?
I got the answer to my prev problem, now i have another problem
i had .txt appended to my input file in my makefile. Now i have another problem. on command make it gives error.
0make: *** [a.out] Error 1
why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
检查
fopen
的返回值(好吧,检查any调用的返回值),它可能无法打开文件。Check the return value of
fopen
(well, check the return value of any call), it probably failed to open the file.因为您没有在命令行参数中指定文件,或者因为您指定的文件由于某种原因无法打开。在这种情况下,
fopen
返回NULL
,当您将该NULL
传递给feof
时,程序会崩溃。您必须检查返回值和错误代码,尤其是当函数可能返回 NULL 时。正确的代码可能如下所示:
Because you do not specify the file in a command line arguments, or because the file you have specified there could not be opened for some reason. In that case,
fopen
returnsNULL
, and when you pass thatNULL
tofeof
it crashes the program. You have to check return values and error codes, especially when functions may returnNULL
.The correct code may look something like this: