#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
int main(int argc, char *argv[])
{
// ensure proper usage
if (argc != 2)
{
fprintf(stderr, "Usage: ./recover image\n");
return 1;
}
// remember filenames
char *infile = argv[1];
// open input file
FILE *inptr = fopen(infile, "r");
uint8_t buffer[512];
if (inptr == NULL)
{
fprintf(stderr, "Could not open %s.\n", infile);
return 2;
}
int count=0,flag=0;
FILE *img=NULL;
while(fread(buffer, 512, 1, inptr)==1)
{
fread(buffer, 512, 1, inptr);
if(buffer[0]==0xff && buffer[1]==0xd8 && buffer[2]==0xff && (buffer[3]&0xf0)==0xe00)
{ char filename[8];
if(flag==1)
fclose(img);
sprintf(filename,"%03i.jpg",count);
img=fopen(filename,"w");
flag=1;
count++;
}
if(flag==1)
fwrite(buffer,512,1,img);
}
fclose(inptr);
fclose(img);
return 0;
}
1 Answer
Program never finds a jpg sig, so when it tries to fclose(img);
it seg faults because img is NULL.
Verify your "sig test". This (buffer[3]&0xf0)==0xe00)
is wrong. (0xe00 is two bytes).
But wait there's more! Big problem is back-to-back fread
s here:
while(fread(buffer, 512, 1, inptr)==1)
{
fread(buffer, 512, 1, inptr);
Remember, the fread
in the while
actually reads, so program is reading 1024 bytes before it tests for signature.
-
Thanks a lot! @DinoCoderSaurus Correcting both the reasons solved the problem. Changing 0xe00 to 0xe0 solved the problem! May 6, 2017 at 14:50
-
Can you help solving this segmentation fault ?@DinoCoderSaurushttps://cs50.stackexchange.com/questions/24795/pset5speller-segmentation-fault-valgrind-shows-error-at-line-76-iftmp-chil May 7, 2017 at 14:52