0
#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

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 freads 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.

2
  • Thanks a lot! @DinoCoderSaurus Correcting both the reasons solved the problem. Changing 0xe00 to 0xe0 solved the problem! – Benedict Florance May 6 '17 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 – Benedict Florance May 7 '17 at 14:52

You must log in to answer this question.

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