0

I know this has been brought up a few times before but none of the solutions seem to be relevant to the code that I have written below. My recover.c file compiles, executes and returns all 50 images fine but does not pas the last 3 check50 statements. I can only think that there may be some mismatch between the jpg names and the images they are assigned to but I could be wrong. Any advice would be great!

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

typedef uint8_t BYTE;

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

    if (argv[1] == NULL)
    {
        printf("Invalid card");
        return 1;
    }



    FILE *f = fopen(argv[1], "r");
    BYTE buffer[512];
    int jpgcounter = 0;
    char filename[8];
    char firstJpg = 'f';
    FILE *img = NULL;

    while (fread(buffer, sizeof(BYTE), 512, f) == 512)
    {
        if (
                buffer[0] == 0xff &&
                buffer[1] == 0xd8 &&
                buffer[2] == 0xff &&
                (buffer[3] & 0xf0) == 0xe0
           )
           {
               if (firstJpg == 'f')
               {
                   firstJpg = 't';
               }
               else
               {
                   fclose(img);
               }
               sprintf(filename, "%03i.jpg", jpgcounter);
               jpgcounter++;
               img = fopen(filename, "w");
               fwrite(buffer, sizeof(BYTE), 512, img);
           }
        else if (img != NULL)
        {
            fwrite(buffer, sizeof(BYTE), 512, img);
        }
        else
        {
            continue;
        }
    }
    fclose(img);
    fclose(f);
    free(buffer);
    free(filename);
    return 0;

}
2

It's failing because the program is terminating abnormally, even though it is creating the output files. When I run it, I get this, along with the recovered images:

~/go/test/pset4/jpg/ $ ./recover card.raw
munmap_chunk(): invalid pointer
Aborted

This causes the tests to fail. The problem lies with this code:

free(buffer);
free(filename);

Neither of these two vars are pointers with memory allocated by malloc or any other related functions. The free() function cannot be used with them. So, these two lines of code throw errors.

This is a good lesson that programmers should always check that the program really is terminating normally. ;-)

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

1
  • Face palm. thanks again Cliff B! That has passed all checks now – Steven George Apr 8 at 10:11

You must log in to answer this question.

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