I've just completed pset4 - recover.
I did quite a bit of debugging and was finally able to pass all checkmarks with check50, style50 and Valgrind. After submitting I checked my grade and I received 6/7 (.97) with the error ":( program is free of memory errors. Cause: timed out while waiting for program to exit".
I'm not sure why I'm getting this error as all my testing passes in the terminal. I'm not as concerned with the grade itself as I am about not understanding if I've done something wrong. Can anyone help?
Thanks!
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
// Ensure only 1 command line argument.
if (argc != 2)
{
printf("Error: Use only 1 command line argument.\n");
return 1;
}
// Open memory card.
FILE *card = fopen(argv[1], "r");
if (card == NULL)
{
printf("Could not open file.\n");
return 1;
}
// Declare FILE variable.
FILE *img;
// Allocate memory for buffer.
unsigned char *buffer = malloc(512);
if (buffer == NULL)
{
printf("Not enough memory available.\n");
return 1;
}
// Declarations for use in while loop
bool jpg = false;
int count = 0;
char filename[8];
bool isOpen = false;
// Repeat until end of card:
while (fread(buffer, 1, sizeof(buffer), card) != 0)
{
// Check first 4 bytes of buffer - is it the start of a JPG?
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && ((buffer[3] & 0xf0) == 0xe0))
{
// Closes previous img file.
if (isOpen == true)
{
fclose(img);
}
// Change jpg variable to true.
jpg = true;
// Print the name of the JPEG file into the variable "filename" and add to JPEG counter
sprintf(filename, "%03i.jpg", count);
count++;
// Open previously created "filename" file in order to write to.
img = fopen(filename, "w");
if (img == NULL)
{
printf("Could not open file.\n");
return 1;
}
fwrite(buffer, 1, sizeof(buffer), img);
// Change isOpen to true.
isOpen = true;
}
// If buffer does not equal a jpg header, but jpg is true then do this.
else if (jpg == true)
{
fwrite(buffer, 1, sizeof(buffer), img);
}
}
// Free malloc memory.
free(buffer);
// Close img
fclose(img);
// Close memory card.
fclose(card);
return 0;
}