Skip to content

Instantly share code, notes, and snippets.

@olvlo
Created July 22, 2016 03:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olvlo/b88ee0a34cbe02a0fb4310da3c00c49f to your computer and use it in GitHub Desktop.
Save olvlo/b88ee0a34cbe02a0fb4310da3c00c49f to your computer and use it in GitHub Desktop.
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