Good afternoon/morning,
I'm having problem with Problem set 4 Recover, My code can compile but Segmentation fault (core dumped) keeps going out,
I checked on debug50 and it seems the segfault occurs when hit " sprintf(filename, "%03i.jpg", k);"
I'm very confused. Any tips?
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef uint8_t BYTE;
int BLOCK_SIZE = 512;
int main(int argc, char *argv[])
{
// Ensure proper usage
if (argc != 2)
{
printf("Usage: ./recover IMAGE\n");
return 1;
}
// Open input file
FILE *infile = fopen(argv[1], "r");
if (infile == NULL)
{
printf("Could not open %s.\n", argv[1]);
return 2;
}
//allocate memory for file name and for buffer
char *filename = malloc(8 * sizeof(char));
BYTE *buffer = malloc(BLOCK_SIZE * sizeof(BYTE));
filename = "000.jpg";
int k = -1;
FILE *outfile = fopen(filename, "w");
while (fread(buffer, 1, BLOCK_SIZE, infile) == BLOCK_SIZE)
{
//find the signature
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xe0) == 0xe0)
{
fclose(outfile);
//make outfile name
k = k + 1;
sprintf(filename, "%03i.jpg", k);
//printf("%i\n",k);
//open outfile
outfile = fopen(filename,"w");
}
if (outfile == NULL)
{
fclose(infile);
printf("Could not create %s.\n", filename);
return 5;
}
//write outfile
fwrite(&buffer, sizeof(BYTE), BLOCK_SIZE, outfile);
}
// Close outfile
fclose(outfile);
fclose(infile);
free(filename);
free(buffer);
return 0;
}