0

I can't seem to find the reason of why I'm getting the segmentation fault in my code. The moment my code starts to write the bytes of buffer, I encounter the fault

Any help is really appreciated.

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

int main(int argc, char* argv[])
{
    // argc check
    if(argc != 2)
    {
        fprintf(stderr, "Invalid argument count. It should be ./recover card.raw\n");
        return 1;
    }
    // open input file
    FILE *input = fopen(argv[1], "r");
    if(input == NULL)
    {
        fprintf(stderr, "Couldn't open the file.\n");
        return 4;
    }
    // allocate 512B memory
    int *buffer = malloc(512);
    if (buffer == NULL)
    {
    fclose(input);
    fprintf(stderr,"Cannot create a buffer.\n");
    return 3;
    }
    // read the card.raw, while checking the EOF
    while(fread(buffer, 512, 1, input) == 1)
    {
    // print the first 4 bytes
    printf("%#x\n",buffer[0]);
    //check the first 4 bytes for .jpeg
    if((buffer[0] & 0xf0ffd8ff) == 0xe0ffd8ff)
    {
        // create a new file
        char c[3];
        int i = 0;
        sprintf(c, "%03i.jpg", i);
        FILE *image = fopen(c, "w");
        if (image == NULL)
        {
            fclose(input);
            fprintf(stderr, "Could not open an image file.\n");
            free(buffer);
            return 2;
        }
        do
        {
            // write the buffer to the new file
            fwrite(buffer, 512, 1, image);
            // read the next 512B of input
            fread(buffer, 512, 1, input);
        }// check for the end of jpeg.
        while(!((buffer[0] & 0xf0ffd8ff) == 0xe0ffd8ff));
        // close the output file
        fclose(image);
        // change the output file name for the next output
        i++;
        }
    }
    // free the heap
    free(buffer);
    // close the input file
    fclose(input);
}

1 Answer 1

2
 char c[3];

is the guilty declaration of segfault, the array space is insufficient should be resolved with:

char c[8];

keep in mind that we must store something like 001.jpg which are seven characters plus the end character of string \0

2
  • Thank you MARS, I fixed it. After a few fixes in the code, I can recover some images now. On the other hand, I searched through some solutions and it turns out I can recover only one of every 2 images. My algorithm somehow recovers one image and skips the next one. I think it has to do with (buffer[0] & 0xf0ffd8ff) == 0xe0ffd8ff check. Commented Sep 11, 2017 at 7:20
  • cont. : also with the malloc function. But thank you for your help again :) Commented Sep 11, 2017 at 7:27

You must log in to answer this question.

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