0

So far I believe my code should be operational. I thought I got it down but no matter what I change I continue to have this output that says " UndefinedBehaviorSanitizer:DEADLYSIGNAL ... ". Anyone know what that may mean and how to fix it? Or atleast what is my issue?

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

// ensure proper usage
    if (argc != 2)
    {
        fprintf(stderr, "Usage: %s image\n", argv[0]);
        return 1;
    }

    // if image can not be opened for reading
    // open memory file

    FILE *file = fopen(argv[1], "r");
    if (file == NULL)
    {
        fclose(file);
        fprintf(stderr, "Could not open %s.\n", argv[1]);
        return 2;
    }

    BYTES bytes[512];
    char filename[8];
    int searchJpeg = 0;// for true or false condition
    int count = 0;
    FILE *img = NULL;

    while (fread(&bytes, 512, 1, file) == 1)
    {

        if (searchJpeg == 1)
        { // if start of new JPEG
        //find beginning of JPEG
            if (bytes[0] == 0xff && bytes[1] == 0xd8 && bytes[2] == 0xff && (bytes[3] == 0xe0 || bytes[3] == 0xe1))
            {
                //yes

            searchJpeg = 0;

            sprintf(filename, "%03d.jpg", count);
            img = fopen(filename, "w");//open a new JPEG
            fwrite(&bytes, 512, 1, img); //write 512 bytes until new JPEG is found


            }
            else
            {//if no, there is nothing there
            printf("Nothing found.\n ");
            }
        }

        else
        {
            //JPEG was already found
            if (bytes[0] == 0xff && bytes[1] == 0xd8 && bytes[2] == 0xff && (bytes[3] == 0xe0 || bytes[3] == 0xe1))
             {
            fclose(img);// close JPEG
            count++; // increment the file number

            sprintf(filename, "%03d.jpg", count);
            img = fopen(filename, "w");//open a new JPEG
            fwrite(&bytes, 512, 1, img); //write 512 bytes until new JPEG is found

              }
            else
             {//no didn't already find a JPEG
            fwrite(&bytes, 512, 1, img);
             }

        }


    }
    fclose(img);
    free(bytes);


}
0

Simply put, when the code reads in the garbage data at the beginning of the input file, it's trying to write it out, but no output file has been opened yet. That's causing this error.

You need to adjust the code to handle disposing of the garbage data that comes before the first signature.

When you have a situation like this, you should either run it in debug, or, if you can't replicate the error in the debugger (this sometimes happens), insert some printf statements to identify which line is causing the error.

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.