0

I am getting a 'Segmentation fault (core dumped) error'

I know that means I am accessing memory I shouldn't. I feel like it has something to do with my fread or fwrite functions.

'''

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

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

    if (argv[1] == NULL)
    {
        printf("File entered does not exist\n");
        return 1;
    }

    FILE *file = fopen(argv[1], "r");
    typedef uint8_t BYTE;
    BYTE buffer[512];
    char filename[8];
    int i = 0;
    FILE *img;
    while (fread(buffer, 1, 512, file) == 512)
    {
        // check if first three bytes are 0xff 0xd8 0xff
        // check if 4th byte is 0xe0, 0xe1, 0xe2, ..., 0xef
        // if those 4 bytes are found then start writing these bytes to a file ###.jpg
        // once you see the 4 bytes again, stop writing to the current file and make a new file ###.jpg to write to
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            if (i == 0)
            {
                sprintf(filename, "%03i.jpg", i);
                img = fopen(filename, "w");
                i += 1;
            }
            else
            {
                fclose(img);
                sprintf(filename, "%03i.jpg", i);
                img = fopen(filename, "w");
                i += 1;
            }
            fwrite(buffer, 1, 512, img);
        }
        else
        {
            img = fopen(filename, "w");
            fwrite(buffer, 1, 512, img);
        }
    }
    fclose(img);

    return 0;
}

'''

Any ideas?

1 Answer 1

0

I think there's an issue with your second else statement. Since this else statement has you writing when you are NOT at the start of a new jpeg file, you should make sure you've already opened and started writing to at least one image.

You must log in to answer this question.

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