0

/** * recover.c * * Computer Science 50 * Problem Set 4 * * Recovers JPEGs from a forensic image. */

include

include

include

int main(int argc, char* argv[]) { // Ensure proper usage if(argc != 2) { printf("You need ./recover and an infile\n"); return 1; }

//remember file name
char* infile = argv[1];

//open input file
FILE* inptr = fopen("card.raw", "r");
if(inptr == NULL)
{
    printf("Could not open %s. \n", infile);
    return 2;
}

//define buffer
unsigned char buffer[512] = {0};
//jpegs
char jpg[8] = {0};
//keep track of the filenumbers
int filenumber = 0;
//pointer for outfile
FILE* outptr; 

//repeat until end of file
while(fread(&buffer, sizeof(buffer), 1, inptr) == 1)
{//read 512 bytes into a buffer

    //Finding the beginning of a jpg
    if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] == 0xe0 || buffer[3] == 0xe1))
    {
        //opens new jpg; creates file name for jpgs
        sprintf(jpg, "%03d.jpg", filenumber);

        //opens a new file
        outptr = fopen(jpg, "w");
        if (NULL == outptr)
        {
            printf("Cannot open jpg\n");
            return 1;
        }

        //write into outfile
        fwrite(buffer, sizeof(buffer), 1, outptr);

        //increment jpgs
        filenumber++;
    }

    else
    {
        if(NULL != outptr)
        {
            fwrite(buffer, sizeof(buffer), 1, outptr);
        }
    }
}

fclose(inptr);

fclose(outptr);

return 0;

}

1

Here's the problem:

FILE* outptr; 
...
if(NULL != outptr)
    {
        fwrite(buffer, sizeof(buffer), 1, outptr);

When created, outptr contains garbage data. It isn't automatically set to NULL, so when the first block doesn't have a signature and no file is opened, it drops down to the IF statement. Since outptr contains garbage data, it doesn't == NULL and the fwrite() is called, which triggers the seg fault.

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

| improve this answer | |
2

Also, you need to check the 4th byte for 0xe0 to 0xef and not only 0xe1 and 0xe0.

| improve this answer | |
  • Very true, but that's a totally different question. ;-) – Cliff B Mar 6 '16 at 23:16
  • A down vote??? This was a really good point! Too many people are overlooking this from the pset instructions, just because Zamyla's video (recycled from last year's pset, which has changed), says two signatures. This is an important lesson. Don't assume anything from casual conversations when spec'ing a project - READ THE ACTUAL SPECIFICATION! I gave you an upvote, Akshit. – Cliff B Mar 21 '16 at 23:08

You must log in to answer this question.

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