0

I'm currently a student working on the wk5 pset recover for cs50. I've written out my code but have encountered a segmentation fault. How do I go about debugging this? I've checked out all the other responses on the forum but still cannot understand where I am going wrong

typedef uint8_t BYTE;
typedef BYTE BLOCK[512];

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        printf("Incorrect input\n");
        return 1;
    }

    FILE *jpeg = fopen(argv[1], "r");
    if (!jpeg)
    {
        printf("Error cannot open file\n");
        return 1;
    }

    BLOCK buffer;

    int n = 0;
    FILE *current_img = NULL;
    char filename[8];

    while(fread(&buffer, sizeof(BLOCK), 1, jpeg) == 1)
    {
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            if (n == 0)
            {
                sprintf(filename, "%03i.jpg", n);
                current_img = fopen(filename, "w");
                fwrite(buffer, sizeof(BLOCK), 1, current_img);
                n++;
            }
            else
            {
                fclose(current_img);

                sprintf(filename, "%03i.jpg", n);
                current_img = fopen(filename, "w");
                fwrite(buffer, sizeof(BLOCK), 1, current_img);
                n++;
            }
        }
        else
        {
            fwrite(&buffer, sizeof(BLOCK), 1, current_img);
        }

    }
    fclose(current_img);
    fclose(jpeg);


}

Debug50 tells me this line is the problem"

fwrite(&buffer, sizeof(BLOCK), 1, current_img);

Thank you guys!

Terry Chung
  • 27
  • 1
  • 5

1 Answers1

0

In the debugger, look at the value of current_img before the offending line executes.

If the first block it reads is not a jpg signature (which it is not in the provided card.raw), where will control go? What is the value of current_img in that case?

DinoCoderSaurus
  • 6,110
  • 2
  • 10
  • 15