如何在运行时删除分段错误 [英] How Do I Remove Segmentation Error During Runtime

查看:165
本文介绍了如何在运行时删除分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个代码,一次读取多个图像,即p [1] ..... p [14].编译期间没有错误.
我在运行时遇到的错误是细分错误".
代码是:

I wrote a code to read multiple images at a time i,e p[1].....p[14] .No errors during compilation.
Error i got during run time is "segmentation fault".
code is:

#include<stdio.h>
int main(void)
{
FILE *fp;
int i;
char ch;
for(i=1;i<15;i++)
{
char fn[100];
sprintf(fn,"p[%d].gif",i);
fp=fopen("p[i].gif","rb");
fread(&ch,sizeof(ch),1,fp);
}
}

推荐答案

要做的第一件事是引入一些错误检查.
由于您为读取的每个文件使用相同的文件名:
The first thing to do is introduce some error checking.
Since you use the same file name for every file you read:
fp=fopen("p[i].gif","rb");

然后您不关闭它,在某个时候给出错误.
但是...如果文件不存在怎么办? fopen将返回空值,将其传递给fread会出现分段错误...

您可以先用sprintf调用的结果替换固定文件名,这将有所帮助-但您确实需要检查fopen的返回值,否则以后会有更多问题.完成后,关闭该死的文件!

And you don''t close it, that''s going to give an error at some point.
But...what happens if the file doesn''t exist? fopen will return a null, you will pass it to fread and you will get a segmentation fault...

You can start by replacing the fixed file name with the result from the sprintf call and that will help - but you do need to check the return value from fopen or you will have more problems later. And close your damn files when you have finished with them!


这篇关于如何在运行时删除分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆