Skip to main content
1 of 2

Problem Set 4 - Recover (timed out while waiting for program to exit)

After spending almost a week working on the code for the Recover exercise, I have finally made it work. However, when I check with check50, I get the error: :( program is free of memory errors timed out while waiting for program to exit.

I know that I could probably find what's wrong by using the debug50 debugger, but for some reason it won't work. Now, regarding the error, the magic duck says that there is probably a loop in my program that never exits.

I' m looking at it for quite some time. I tried changing things here and there, but the only thing I actually managed to do was to break the code, so I had to fix it again and again, without getting rid of the memory error.

I would be glad if someone could help me with this. Here's my code:

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

// Let's avoid typing magic numbers!
#define FAT_FILE_BLOCK_SIZE 512
#define FILENAME_LENGTH 8

typedef uint8_t BYTE;

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

    // Accept a single command-line arguement
    if (argc != 2)
    {
        printf("Usage: ./recover <insert filename here>\n");
        return 1;
    }

    // Open the memory card
    FILE *card = fopen(argv[1], "r");
    if (card == NULL)
    {
        printf("Unable to open file.\n");
        return 1;
    }

    BYTE *buffer = malloc(sizeof(BYTE) * FAT_FILE_BLOCK_SIZE);
    if (buffer == NULL)
    {
        fclose(card);
        printf("Unable to store jpeg.\n");
        return 1;
    }

    int counter = 0;
    char new_jpeg_name[FILENAME_LENGTH];

    FILE *jpeg = NULL;
    // While there's still data left to read from the memory card
    while ((fread(buffer, sizeof(buffer), 1, card)) == 1)
    {
        // Check header for JPEG file
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            if (counter > 0)
        {
            fclose(jpeg);
        }
            sprintf(new_jpeg_name, "%03i.jpg", counter);
            counter++;
            jpeg = fopen(new_jpeg_name, "a");
        }
        if (counter > 0)
        {
              fwrite(buffer, sizeof(buffer), 1, jpeg);
        }

    }
     if (jpeg != NULL)
    {
        fclose(jpeg);
    }
    fclose(card);
    free(buffer);
    return 0;
}