0

I have been working on this pset for a while, but I was not able to solve my problem yet. When I compile my recover.c program, it does so without any errors. Although my program creates all images correctly, it does not pass check50. The following message is being displayed while execution:

*** Error in `./recover': munmap_chunk(): invalid pointer: 0x00007fffaea990c0 ***
Aborted

I was hoping you could help me. Thank you!

Here is an excerpt of my code:

    //buffer pointer
    unsigned char block[512];

    //checking if full block of 512 bytes
    while(fread(&block , sizeof(block), 1, infile) == 1)
    {
        //checking if start of new JPEG
        if(block[0] == 0xff && block[1] == 0xd8 && block[2] == 0xff && (block[3] == 0xe0 || block[3] == 0xe1))
        {
            //checking if already a out.file
            if(*numberFiles > 0)
            {

                fclose(img);
                img = NULL;
            }

            //creating new file name
            int sprint = sprintf(filename, "%03i.jpg", *numberFiles);

            //checking if mistake by creating
            if(sprint < 0)
            {
                fprintf(stderr, "could not create file.\n");
                return 1;
            }

            *numberFiles += 1;

            //open new file
            img = fopen(filename, "w");
            if (img == NULL)
            {
                fprintf(stderr, "Could not create file\n");
                return 4;
            }

            //writing into the new file
            fwrite(&block, sizeof(block), 1, img);
        }

        //adding if already a out.file
        else if(*numberFiles > 0)
        {
            fwrite(&block, sizeof(block), 1, img);
        }
    }

    //closing infile
    fclose(img);
    fclose(infile);
    return 0;
3
  • What would happen if the file size is not an integral multiple of 512, say 1100 bytes? Your fread wouldn't return 1 on the 3rd call because EOF is reached early. That is the reason check50 is failing. – letmutx Mar 27 '17 at 10:56
  • Thank you for your helpful comment! I created an additional condition and it works now. – MStud Mar 27 '17 at 11:40
  • Happy to help :) If it worked for you, I'll add the comment as an answer. – letmutx Mar 27 '17 at 12:19
1

If the file size is not a multiple of 512 bytes, the last call to fread wont return 1 causing the loop to terminate before the whole file is processed. This is causing check50 to fail.

You can try calling fread like

while ((bytes_read = fread(block, sizeof(char), 512, infile)) > 0)

and process the bytes read as necessary.

You must log in to answer this question.