0

I don't know why it's showing seg fault. Could anyone please tell me what I've done wrong?

     #include<stdio.h>
    #include<stdint.h>
 #include<stdlib.h>

typedef uint8_t  BYTE;

typedef struct
 {
 BYTE ar[512];
  }
 ARRAY;


   int main()
 {
 FILE* file = fopen("card.raw", "r");
 int s=0;
char title[8];
ARRAY array;
FILE* img=NULL;


while(!feof(file))
{
 fread(&array,sizeof(ARRAY),1,file);

    if(array.ar[0]==0xff && array.ar[1]==0xd8 && array.ar[2]==0xff &&(array.ar[3]==0xe0 || array.ar[3]==0xe1))
 {
    if(img!=NULL)
   {
     {
      fclose(img);
     }
   sprintf(title,"%0.3d.jpg",s);
   FILE* img=fopen(title,"w");
   fwrite(&array,sizeof(ARRAY),1,img);
   s++;
   }

  else
   {

    fwrite(&array,sizeof(ARRAY),1,img);
   }
 }
}
   fclose(file);
   fclose(img);
   return 0;  
  }  
0

img is initially set to NULL. If the first 4 bytes of the first read 512 bytes are not a start of a JPG, the else condition inside the while loop is executed so basically you're trying to write to NULL which results in a segmentation fault.

2
  • if i dont give img an initial value it gives me an error. What value should i assign it when i initialise it? – Amrita Sep 30 '14 at 18:26
  • I've edited my program accordingly^, yet still I'm getting a seg fault. – Amrita Sep 30 '14 at 18:39
0

I had declared FILE* again in the if condition.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .