0

Everytime I try to run this code, it gives me a segmentation fault error. What is wrong with my logic?

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

int main(int argc, char *argv[])
{
    // Ensures proper usage
    if (argc != 2)
    {
        fprintf(stderr, "Usage: ./recover card.raw\n");
        return 1;
    }

    // Remembers arguments
    char *raw_image = argv[1];

    // Opens image
    FILE *raw_file = fopen(raw_image, "r");
    if (raw_file == NULL)
    {
        fclose(raw_file);
        fprintf(stderr, "Could not open %s.\n", raw_image);
        return 2;
    }

    // Counts JPEGs
    int jpegCounter = 0;

    unsigned char buffer[512];

    // Stores JPEG names
    char jpegs [10];

    // Creates output file for JPEGs
    FILE *img = NULL;

    while (1)
    {
        // Reads card.raw
        fread(&buffer, 512, 1, raw_file);

        // Checks if JPEG
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && 
        (buffer[3] & 0xf0) == 0xe0)
        {
            // Names JPEGs by number
            sprintf(jpegs, "%03i.jpg", 2);

            // Opens found jpeg
            img = fopen(jpegs, "w");
            fwrite(&buffer, 512, 1, img);

            // Adds to counter
            jpegCounter++;
        }
        else
        {
            fwrite(&buffer, 512, 1, img);
        }

        // on end of file terminate program
        if (feof(raw_file))
        {
            fclose(raw_file);
            fclose(img);
            return 0;
        }
    }

    // close file
    fclose(raw_file);

    // Success!
    return 0;
}

1 Answer 1

1

First, you should always isolate which line of code is causing the seg fault.

In this code, the logic is to look for a signature. If a signature is not found, then execute the else clause.

Now, let's look at the else clause.

    else
    {
        fwrite(&buffer, 512, 1, img);
    }

This will attempt to write the buffer contents.

So consider what happens with the first block of data. There's no signature because it's garbage data. The code first checks for a signature and finds none. It then executes the fwrite, but no file has been opened yet. So, img is a null pointer. That throws a seg fault.

There's nothing in the code to handle discarding the garbage data that's read before the first signature.

There may be other issues, but this is your seg fault.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

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