Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:
C++
#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);
}
}
Posted
Updated 1-Sep-14 19:46pm
v2
Comments
[no name] 2-Sep-14 1:24am    
Please explain in words what this code is meant to do because it makes no sense. Crazy code can be often compiled. Have you made any effort to debug this? The debugger will tell you immediately what is going on.

1 solution

The first thing to do is introduce some error checking.
Since you use the same file name for every file you read:
C++
fp=fopen("p[i].gif","rb");
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!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900