Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
valgrind returns several invalid fread/fwrite/free()
/**
* recover.c
*
* Computer Science 50
* Problem Set 4
*
* Recovers JPEGs from a "card.raw" forensic image.
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
typedef uint8_t BYTE;
void showmethepix(FILE* source, FILE* target, BYTE* buffer, int ctr, char* imagenr);
int main(void)
{
// open forensic image file
FILE* source = fopen("card.raw", "r");
if (source == NULL)
{
printf("Could not open card.raw\n");
return 2;
}
// create counter for filename, buffer to store filename
int ctr = 0;
char imagenr[8];
// sprintf filename to buffer, open outfile and verify opening
sprintf(imagenr,"%i.dmp", ctr);
FILE* target = fopen(imagenr, "a");
if (target == NULL)
{
fclose(source);
fprintf(stderr, "Could not create %s.\n", imagenr);
return 3;
}
// read target file into buffer
BYTE *buffer = malloc (512 * sizeof(BYTE));
if (buffer == NULL)
{
printf ("Could not generate buffer storage\n");
fclose(source);
fclose(target);
}
// check for JPG magic numbers, zeroes block
showmethepix(source, target, buffer, ctr, imagenr);
// wrap up upon return (i.e., when source file is only 0x00)
free(buffer);
fclose(source);
fclose(target);
remove("0.dmp");
return 0;
}
void showmethepix(FILE* source, FILE* target, BYTE* buffer, int ctr, char* imagenr)
{
fread(buffer, 512, 1, source);
// if block contains info (i.e., not zeroes), write to target outfile
if (!feof(source))
{
// initialize new file if block starts with .jpg magic numbers
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] >= 0xe0 && buffer[3] <= 0xef))
{
fclose(target);
sprintf(imagenr,"%'.3i.jpg", ctr);
target = fopen(imagenr, "a");
ctr++;
}
// write chunk to outfile and match next chunk
fwrite(buffer, 512, 1, target);
showmethepix(source, target, buffer, ctr, imagenr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment