0

My program compiles, but wherever it runs I recieve a segmentation fault error. However i cannot see where the source of the problem is:

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

int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        fprintf(stderr, "Format: recover filename\n");
        return 1;
    }
    typedef uint8_t BYTE;
    char *infile = argv[1];
    FILE *inptr = fopen(infile, "r");
    if (inptr == NULL)
    {    
        fprintf(stderr, "Could not open %s.\n", infile);
        return 2;
    }
    char filename[8];
    BYTE buffer[512] = {};
    int jpeg_no = 0;
    FILE *img = NULL;
    while (fread(&buffer, 512, 1, inptr) == 512)
    {
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff &&         (buffer[3] & 0xf0) == 0xe0)
        {
                jpeg_no++;
                sprintf(filename, "%03i.jpg", jpeg_no);
                img = fopen(filename, "w");
                fwrite(&buffer, 512, 1, img);
                fclose(img);
        }
        else if (buffer[0] == 0x00)
        {
            break;
        }
        else
        {
            fwrite(&buffer, 512, 1, img);
        }
    }
fclose(img);
return 0;

}

0

The loop condition should be fread(&buffer, 512, 1, inptr) == 1 or fread(&buffer, 1, 512, inptr) == 512. The first number is the block size, the second is the number of blocks to read, it returns the number of blocks read. If all the bytes were read, fread will return that second number. In our case, either would work, as we always deal with 512 byte blocks.

You immediately fclose the image after writing its first block. When the other fwrite tries to write the next block, it will fail. fclose when finding a new header while img is non-NULL (or jpeg_no is no longer 0). I guess that could be where your error happens.

First file should be 000.jpg, so increment jpeg_no after string-printing the file name.

Also, you fclose(img) at the end without checking whether img is non-NULL (another point where it could crash), while you don't fclose(inptr) at all.

BTW, the buffer[0] == 0x00 part does not make sense to me. fread does not write zeroes to the buffer when it hits EOF, nor do zeroes indicate file end.

You must log in to answer this question.

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