While using debug50 to check my code, I realized that it would encounter segmentation fault when it reaches "fwrite(buffer, 512, 1, photo);" for the second time. There's no problem on the first time though. Below is my code:

#include <stdio.h>
#include <stdlib.h>
#include <math.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 filename
    char *recovername = argv[1];

    // open location
    FILE *recover = fopen(recovername, "r");
    unsigned char buffer[512];
    if (recover == NULL)
        fprintf(stderr, "Could not open %s.\n", recovername);
        return 2;

    int a=0;
    // find 
    while (fread(buffer, 512, 1, recover) == 1)
        //read file by 512 bytes
        FILE* photo = NULL;

        //check if it's a jpeg
        if(buffer[0]==0xff && buffer[1]==0xd8 && buffer[2]==0xff && (buffer[3] & 0xf0)==0xe0)
            char filename[8];
            sprintf(filename, "%03i.jpg",a);
            photo = fopen(filename, "a");

            fwrite(buffer, 512, 1, photo);

    // close infile

    // success
    return 0;

Since it should persist over multiple iterations, move FILE* photo = NULL; above your loop. Otherwise you're creating a new variable each iteration and set it to NULL, which makes fwrite fail.

Second segmentation fault when fclose(filename);. Replace it with something like if (a > 0) fclose(photo);

Oh, and off by one. First file should be 000.jpg. Move a++ below sprintf. But that doesn't cause a segmentation fault.

You must log in to answer this question.

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