0

After running it, I got the error massage "double free or corruption (top) Aborted". And I only got 000.jpg. Need some advice, thanks.

int main(int argc, char *argv[])
{
    //ensure proper usage
    if (argc != 2)
    {
        fprintf(stderr, "Usage: ./recover image\n");
        return 1;
    }

    //remember forensic image's name
    char *fimg = argv[1];

    //open forensic image
    FILE *file = fopen(fimg, "r");
    if (file == NULL)
    {
        fprintf(stderr, "Could not open %s.\n", fimg);
        return 2;
    }

    unsigned char buffer[512];
    int n = 0; //count the number of JPEG file

    char tempstring[8];
    char *filename = tempstring;

    FILE *jf = NULL;

    //repeat until end of card
    while (fread(buffer, 512, 1, file))
    {
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            if (jf != NULL)
            {
                fclose(jf);
                n++;
            }

            sprintf(filename, "%03i.jpg", n);
            jf = fopen(filename, "w");
            if (jf == NULL)
            {
                fprintf(stderr, "Could not open %s.\n", filename);
                return 3;
            }

            fwrite(buffer, 512, 1, jf);
        }

        else
        {
            if (jf != NULL)
            {
                fwrite(buffer, 512, 1, jf);

                if (fread(buffer, 512, 1, file) != 512)
                {
                    fclose(jf);
                    n++;
                }
            }
        }
    }

    //close any remaing files
    fclose(jf);

    return 0;
}
1

I see two problems with your code. Both are here:

            if (fread(buffer, 512, 1, file) != 512)
            {
                fclose(jf);
                n++;
            }

First, if the fread works correctly, it will return 1 here, not 512. The value returned is the number of elements returned. The third parameter tells how many elements to read, not the second. But this is a moot point because of the next issue.

Second, is this entire code block even necessary? The while loop statement performs the same function. When a read doesn't return 1, it will be because of the EOF condition and will return 0, terminating the loop. This code is therefore redundant. In fact, it causes problems.

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

You must log in to answer this question.

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