0

Can anyone help? I keep getting a segmentation fault when trying to run recover.c. It compiles fine. My code is below. I do plan to add in the error returns once I can get this to work properly as well. Also, side note, if anyone happens to know how to implement bools in C that would be great. I kept getting an udclared identifier error even when including <stdbool.h>

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

typedef uint8_t BYTE;

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        printf("Usage: ./recover image");
        return 1;
    }



    FILE *f = fopen(argv[1], "r");
    BYTE buffer[512];
    int jpgcounter = 0;
    char* filename[8];
    char firstJpg = 'f';
    FILE *img = NULL;

    while (fread(buffer, sizeof(BYTE), 512, f) == 512)
    {
        if (
                buffer[0] == 0xff &&
                buffer[1] == 0xd8 &&
                buffer[2] == 0xff &&
                (buffer[3] & 0xf0) == 0
           )
           {
               if (firstJpg == 'f')
               {
                   firstJpg = 't';
               }
               else
               {
                   fclose(img);
               }
               sprintf(*filename, "%03i.jpg", jpgcounter);
               jpgcounter++;
               img = fopen(*filename, "w");
               fwrite(buffer, sizeof(BYTE), 512, img);
           }
        else
        {
            fwrite(buffer, sizeof(BYTE), 512, img);
        }
    }
    fclose(img);
    fclose(f);


}
2

This is a common error in this pset. Look at the following code closely.

    else
    {
        fwrite(buffer, sizeof(BYTE), 512, img);
    }

The pset spec says that the input file starts with garbage data, and to search for a signature. With that in mind, think about what happens when the first data block is processed. There is no signature and no output file has been opened. So, what happens when the code tries to write to img??? It seg faults. Maybe the code should check to see if the file has been opened somehow?

The next problem is here:

char* filename[8];

This creates an array of 8 pointers to chars, not 8 chars. I'll let you think about that.

As for the bool issue, I'd have to see how you're trying to implement it, perhaps in a new question?

If this answers your question, please click on the check mark to accept. Let's keep up on fourm maintenance. ;-)

2
  • Thanks! I definitely would have spent far too long on that initial garbage data problem. Unfortunately the same segmentation fault is still ocurring. – Steven George Apr 7 at 17:58
  • Just realised my own error on line: (buffer[3] & 0xf0) == 0 should have been 0xe0. Thanks for the suggestion on the other errors as well – Steven George Apr 7 at 18:33

You must log in to answer this question.

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