0

I'm sorry to bring about yet another segmentation fault but I cannot for the life in me find the error (Even valgrind is kinda malfunctioning).

Here's my code-

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

int main(int argc, char *argv[])
{
    //Check if arguements are correct.
    if (argc != 2)
    {
        fprintf(stderr, "Usage: ./recover image\n");
        return 1;
    }

    //Open the provided file.
    FILE *file = fopen(argv[1], "r");
   
    //Check if file available
    if (file == NULL)
    {
        fprintf(stderr, "No such File!");
        return 1;
    }
   
    //Make Output file for jpeg
    FILE *img = NULL;
   
    //Create Buffer and Filename
    unsigned char buffer[512];
    char filename[8];
    
    //Counter for filename
    int counter = 0;
    
    //read file
    while (fread(buffer, 512, 1, file) == 1)
    {
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            if (counter == 0)
            {}
            else
            {
                fclose(img);
            }
            sprintf(filename, "%03i.jpg", counter);
            img = fopen(filename, "w");
            counter++;
        }
        fwrite(&buffer, 512, 1, img);
    }
    fclose(file);
    fclose(img);
    return 0;
}

Is it something subtle and small that's causing an error or is my code entirely wrong? Cuz it's worrying to see valgrind returning absolutely nothing. Thanks in advance!

0

debug50 may be a better tool at this point, so you can find where program is crashing.

Assuming the first block is not a jpg signature, where does program control go when this if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0) is false?

You must log in to answer this question.

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