0

Can't understand what's wrong in my code: it's compiling but not creating jpgs, the check says "failed to execute program due to segmentation fault". Please help to understand - THANKS IN ADVANCE!

Here's my code:


#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef uint8_t  BYTE;

int main(int argc, char *argv[])
{
    if (argc !=2) //checking if there's exactly one command-line argument
    {
        printf("Missing argument!");
        return 1;
    }
    else
    {
        char *input_file = argv[1];
        FILE *input_ptr = fopen(input_file, "r");
        if (input_ptr == NULL) // checking if the forensic image can be opened for reading
        {
            printf("Error: cannot open %s\n", input_file);
            return 2;
        }
        BYTE buffer[512];
        int n = 0;
        FILE *img = NULL;
        char filename [8];
        while (fread(buffer, sizeof(BYTE), 512, input_ptr) != 0) // loop to be repeated until the end of file
        {
            if (buffer[0] == 0xff && buffer[1] == 0xdf && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0) // check if it's the start of jpg
            {
                if (n == 0) // if it's the 1st jpg
                {
                    sprintf(filename, "%03i.jpg", n);
                    img = fopen(filename, "w");
                    fwrite(buffer, sizeof(BYTE), 512, img);
                    n++;
                }
                else // if it's not the 1st jpg
                {
                    fclose(img);
                    sprintf(filename, "%03i.jpg", n);
                    img = fopen(filename, "w");
                    fwrite(buffer, sizeof(BYTE), 512, img);
                    n++;
                }
            }
            else if (img != NULL) //if it's not a start of jpg, so need to keep copying bytes into a jpg that's already been discovered
            {
                fclose(img);
                img = fopen(filename, "a"); // closing and re-opening img to append instead of writing
                fwrite(buffer, sizeof(BYTE), 512, img);
            }
        }
        fclose(img);
        fclose(input_ptr);
        return 0;
    }
}
0

The seg fault happens because no output file is being opened and the code is trying to close the last output file.

No files are being opened because no signature is ever found. There's a typo in the if statement that checks for signatures.

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

2
  • I've changed my code but still not passing the check - now my program is timing out :( – J_K Dec 30 '20 at 14:13
  • I'll close this thread and open another one as now the problem is different... anyway thanks for your support! – J_K Dec 30 '20 at 14:27

You must log in to answer this question.

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