0

My code compiles, but whenever I run Check50, I get a segmentation fault error for each category. Would definitely appreciate any help identifying where the problem can be fixed!

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

int BLOCK = 512;
int counter = 0;
typedef uint8_t BYTE;
char *JPEGfile;
FILE *filename = NULL;

// Define "buffer" as block of 512 bytes
BYTE buffer[512];

int main(int argc, char *argv[])
{


    if (argc != 2) {
        printf ("Usage: ./recover image\n");
        return 1;
    }

    // Open memory card
    FILE *card = fopen(argv[1], "r");

    // Check if card exists
    if (card == NULL) {
        printf ("Could not open %s\n", argv[1]);
        return 1;
    }

    // Loop
    while (fread(&buffer, sizeof(BYTE), BLOCK, card) == BLOCK) {
        // Read the file (512 bytes) into buffer

        // Look for beginning of JPEG
        if (buffer[0] == 0xff &&
            buffer[1] == 0xd8 &&
            buffer[2] == 0xff &&
            (buffer[3] & 0xf0) == 0xe0) { // Starts with header 0xff 0xd8 0xff 0xe0-f

        // If 512 bytes is start of JPEG
            // If this is the first JPEG
            if(counter < 1) {
                // Make new JPEG file to start writing to
                sprintf(JPEGfile, "%03i.jpg", counter); // Start with "000.jpg" going up

                // Open that new file to start writing to it
                filename = fopen(JPEGfile, "w");

                // Write into the file
                fwrite(&buffer, sizeof(BLOCK), BLOCK, filename);

                counter++;
            }
            else {

                // Close previous file
                fclose(filename);

                // Make new JPEG file to start writing to
                sprintf(JPEGfile, "%03i.jpg", counter); // Start with "000.jpg" going up

                // Open that new file to start writing to it
                filename = fopen(JPEGfile, "a");

                // Write into the file
                fwrite(&buffer, sizeof(BLOCK), BLOCK, filename);

                counter++;
            }
        }
        else {
            // If already found a JPEG in previous 512
                // Keep writing to it
                 fwrite(&buffer, sizeof(BLOCK), BLOCK, filename);
        }
    }
    // Close all remaining files
    fclose(card);
    fclose(filename);

    return 0;
}
0

It is not able to check if a jpeg has already been opened or not. For this, set as if-else where you check if counter is 0 or greater than 0. if it is greater than zero, fwrite, else break.

If this was helpful, click the checkmark.

You must log in to answer this question.

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