When I compile and run my program, I get a segmentation fault. Valgrind doesn't show any problems. Any thoughts? I'm going crazy trying to figure out the problem.
The point of the program is to recover JPEGS from a "forensic image" called card.raw . When I run check50 on the code the program fails to meet the requirements due to a seg fault.
This is my code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int jpeg_count = 0;
if(argc != 2)
{
printf("Usage: ./recover image\n");
return(1);
}
FILE *original;
original = fopen(argv[1], "r");
if(original == NULL)
{
printf("Error! Cannot open file.\n");
return(1);
}
unsigned char buffer[512];
char *filename = malloc(8);
fread(buffer, sizeof(buffer), 512, original);
FILE *img;
while(1)
{
if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] &0xf0) == 0xe0)
{
if(jpeg_count == 0)
{
sprintf(filename, "%03i.jpg", 0);
img = fopen(filename, "w");
fwrite(buffer, sizeof(buffer), 512, img);
jpeg_count++;
}
else if(jpeg_count > 0)
{
fclose(img);
sprintf(filename, "%03i.jpg", jpeg_count);
img = fopen(filename, "w");
fwrite(buffer, sizeof(buffer), 512, img);
jpeg_count++;
}
}
if(feof(original))
{
fclose(img);
fclose(original);
free(filename);
break;
}
}
}