As the title says, I've been trying to write a program in C that turns a file into multiple JPGs for a CS exercise. I've closed and freed everything I've worked with, but I'm still getting a segmentation fault, and I'm not quite sure why. Any advice wold be of great help.
EDIT
I already found the answer, it's the fact that there's a possibility that the first block of bytes has no header, which makes the program go to the "else" conditional and write 512 bytes of nothing into a file that doens't exist. The solution was to turn
else
into
else if (block[0] != 0xff && block[1] != 0xd8 && block[2] != 0xff && (block[3] & 0xf0) != 0xe0 && filenumber != 0)
Hopefully this helps somebody!
typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
    // Checks for correct argv usage
    if (argc != 2)
    {
        printf("Usage: filter [file]\n");
        return 1;
    }
    FILE *f = fopen(argv[1], "r");
    if (f == NULL)
    {
    printf("Invalid file\n");
    return 1;
    }
    int filenumber = 0;
    BYTE *block = malloc(512 * sizeof(BYTE));
    char *filename = NULL;
    FILE *img = NULL;
    while (fread(&block, sizeof(BYTE), 512, f) == 512)
    {
        if (block[0] == 0xff && block[1] == 0xd8 && block[2] == 0xff && (block[3] & 0xf0) == 0xe0)
        {
             if (filenumber == 0)
             {
                filename = malloc(8);
                sprintf(filename, "%03i.jpg", filenumber);
                img = fopen(filename, "a");
                if (img == NULL)
                return 1;
                fwrite(&block, sizeof(BYTE), 512, img);
                filenumber++;
             }
             else
             {
                 fclose(img);
                 sprintf(filename, "%03i.jpg", filenumber);
                 img = fopen(filename, "a");
                 if (img == NULL)
                 return 1;
                 fwrite(&block, sizeof(BYTE), 512, img);
                 filenumber++;
             }
        }
        else
        {
            fwrite(&block, sizeof(BYTE), 512, img);
        }
    }
        fwrite(&block, sizeof(BYTE), fread(block, sizeof(BYTE), 512, f), img);
        free(filename);
        free(block);
        fclose(img);
        fclose(f);
        return 0;
}
