Edit: It has been resolved. I figured it out. Anyone who has similar problem may check my answers below. Try to skip over my code to avoid spoiling yourself.
//
//
//
//
I have been stuck with Recover since last week. My program outputs a segmentation fault whenever I run it. Can anyone please help take a look and make some suggestions? Thanks in advance. Here is my code:
#include <stdio.h>
#include <stdlib.h>
//main function
int main(int argc, char *argv[])
{
//declaring input and output file pointers
FILE * inptf, *otptf = NULL;
//checks if user entered prompt
if (argc != 2)
{
printf("Usage: ./recover image\n");
return 1;
}
//open input file to be read
inptf = fopen(argv[1], "r");
//check if file is readable
if (inptf == NULL)
{
printf("File not Found.\n");
return 2;
}
//count images found
int img_count = 0;
//store image name
char img_name[8];
//allocates memory for 1 block of data
unsigned char * block = malloc(512);
//loop to read the entire card until the end of file
while (fread(&block, 1, 512, inptf) == 512)
{
//checks for image header
if (block[0] == 0xff && block[1] == 0xd8
&& block[2] == 0xff
&& (block[3] & 0xf0) == 0xe0)
{
//if a non-first image is found
if (img_count > 0)
{
fclose(otptf);
}
//create file name
sprintf(img_name, "%03i.jpg", img_count);
//open output file to write
otptf = fopen(img_name, "w");
//write image into file
fwrite(&block, 1, 512, otptf);
//increment number of image found
img_count++;
}
else
{
//if an image has been found
if (img_count > 0)
{
//continue writing image into memory
fwrite(&block, 1, 512, otptf);
}
}
//free block of memory
free(&block);
//goes to new block
fseek(inptf, 1, SEEK_CUR);
}
//close output image file
fclose(otptf);
//close memory card
fclose(inptf);
return 0;
}
Here are the results from check50:
:) recover.c exists.
:) recover.c compiles.
:) handles lack of forensic image
:( recovers 000.jpg correctly
failed to execute program due to segmentation fault
:( recovers middle images correctly
failed to execute program due to segmentation fault
:( recovers 049.jpg correctly
failed to execute program due to segmentation fault