I'm getting a segmentation fault when trying to run my program for pset4 recover. I've been trying for ages to debug it, but I'm finding it really difficult because when I try to use debug50, after the first line of the while
loop (while (fread(buffer, 1, sizeof(buffer), card))
", it simply skips the whole loop and goes to the bottom of the program.
#include <stdio.h>
#include <stdint.h>
typedef uint8_t BYTE;
char filename[8];
int main (int argc, char* argv[])
{
// Check command-line arguments
if (argc != 2)
{
printf("Usage: ./recover image\n");
return 1;
}
//Open card
FILE *card = fopen("card.raw", "rb");
//Initialize output file
FILE *jpeg;
//Create buffer
BYTE buffer [512];
//Initialize counter
int i = 0;
//Start reading contents of card
while (fread(buffer, 1, sizeof(buffer), card))
{
//Check for the start of the first jpeg
if ((buffer[0] == 0xff) && (buffer[1] == 0xd8) && (buffer[2] == 0xff) && ((buffer[3] & 0xf0) == 0xe0) && i == 0)
{
//Create first jpeg
sprintf(filename, "%03i.jpg", i);
jpeg = fopen(filename, "wb");
//Start writing contents of card into first jpeg file and increment counter
fwrite(buffer, 1, sizeof(buffer), jpeg);
i++;
}
//Check for start of subsequent jpeg files
else if ((buffer[0] == 0xff) && (buffer[1] == 0xd8) && (buffer[2] == 0xff) && ((buffer[3] & 0xf0) == 0xe0) && i > 0)
{
//Close previous file
fclose(jpeg);
//Create new file
sprintf(filename, "%03i.jpg", i);
FILE *out = fopen(filename, "wb");
//Start writing contents of card into new jpeg file
fwrite(buffer, 1, sizeof(buffer), jpeg);
}
//If file is larger than 512B, continue adding blocks to the file until new jpeg is found
else if (i > 0)
{
fwrite(buffer, 1, sizeof(buffer),jpeg);
}
}
//When end of the card is reached, close final jpeg and close card
fclose(card);
fclose(jpeg);
}
Screenshot: