Search code examples
timeoutcs50recover

CS50x recover works with debug50 but times out when testing with check50


I'm currently working on the CS50x recover problem set 4 and I have finished coding and it works when using debug50 but when using check50 it returns this:

:) recover.c exists. :) recover.c compiles. :) handles lack of forensic image :( recovers 000.jpg correctly timed out while waiting for program to exit :( recovers middle images correctly timed out while waiting for program to exit :( recovers 049.jpg correctly timed out while waiting for program to exit

It's all timing out.

And I'm also seeing this in the console because it seems to be stuck at the beginning when I run it. This is my code:

#include <stdlib.h>

int main(int argc, char *argv[])
{
    //check for wrong syntax
    if (argc != 2)
    {
        printf("Usage: ./recover image\n");
        return 1;
    }

    //open card
    FILE *file = fopen(argv[1], "r");
    //check if file exists
    if (file != NULL)
    {
        //vars
        unsigned char buffer[512];
        int files = 0;
        FILE *jpg;

        //read file until end
        while (fread(buffer, 512, 1, file) == 1)
        {
            //check for jpg beginning
            if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
            {
                //vars
                char jpgname[8];
                //generate name
                sprintf(jpgname, "%03i.jpg", files);
                //do only if jpg exists
                if (jpg != NULL)
                {
                    fclose(jpg);
                }
                //create new file with generated name
                jpg = fopen(jpgname, "w");
                //increment file counter
                files++;
            }
            //only do when jpg exists
            if (jpg != NULL)
            {
                //write data to file
                fwrite(buffer, 512, 1, jpg);
            }
        }
        if (jpg != NULL)
        {
            //close final jpg
            fclose(jpg);
        }
        //close file finally
        fclose(file);
    }
    else
    {
        //when file not found
        printf("File not found\n");
        return 1;
    }
} ```

Solution

  • If I was valgrind, I would complain about these if (jpg != NULL) with "Conditional jump or move depends on unitialized value(s)". This FILE *jpg; declares the file pointer, but does not initialize it.

    That will lead to "unpredictable results", which is exactly what you are describing. Result will depend on what memory is assigned to jpg and what that memory contains when the program is run. When run with debug50 that memory more than likely is NULL. Not so check50.