Hello I have written this code to recover the images for pset4 recover.
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
// ensure proper usage
if (argc != 2)
{
fprintf(stderr, "Usage: copy infile outfile\n");
return 1;
}
// remember memory name
char *mem = argv[1];
// open memory card forensic for reading only
FILE *memory = fopen ("card.raw", "r");
if (memory == NULL)
{
fprintf(stderr, "Could not open %s.\n", mem);
return 2;
}
// allocate memory for the blocks that are read from memory
unsigned char* block = malloc(512*sizeof(char));
char filename [4];
int counter = 1;
FILE* image = NULL;
// read the memory card
while (fread(block, 512, 1, memory) == 1)
{
// check for the start of a jpg
if (block[0] == 0xff && block[1] == 0xd8 && block[2] == 0xff && (block[3] & 0xe0) == 0xe0)
{
// close current image if one is open
if (image != NULL)
{
fclose(image);
}
// open new image
sprintf(filename, "%03d.jpg", counter);
image = fopen(filename, "w");
counter++;
}
// write bytes to image
if (image != NULL)
{
fwrite(block, 512, 1, image);
}
}
fclose(image);
fclose(memory);
free(block);
}
This code generates corrupt images. After debugging it I found that the first two bytes directed by the pointer block change after sprintf creates the string filename. I was wondering why is this so?
Thanks
So, Cliff B answered this question and really helped me understand what was worng with this program. But Now I have another question regarding this post and is the reason why this happens. I thought that by using malloc I would be allocating memory in the heap and the array filename is allocated in the stack. Why do the "extra characters" in filename overwrite what is supposedly allocated in the heap?