So this program attempts to recover the file data of some deleted JPEG images using fread() and fwrite(). Going through my code, I can't seem to find an error, but when I run the program with the raw data file, I get the error " free(): double free detected in tcache 2 Aborted (core dumped)"
Looking online this seems the be a memory allocation / freeing issue where some piece of memory is being freed multiple times, but I can't see how that's being done.
Any help would be really appreciated!
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <stdint.h>
typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
// ensure proper usage of program
if (argc != 2)
{
printf("Usage: ./recover img\n");
return 1;
}
// rename and open the memory card
char* inputf = argv[1];
FILE *file = fopen(inputf, "r");
// check that the memory card file is valid
if(file == NULL)
{
printf("Unable to Read Memory Card\n");
return 1;
}
// set up buffer array
BYTE buffer[512];
// initialize jpegcounter
int jpeg = 0;
// allocate memory for filename
char filename[9];
// initialize a file for the bytes to be read into when needed
FILE *JPEGPTR = NULL;
while (fread(buffer, 512, 1, file) == 1)
{
if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
if (jpeg != 0)
{
fclose(JPEGPTR);
}
else
{
sprintf(filename, "i.jpeg", jpeg);
JPEGPTR = fopen(filename, "w");
if (JPEGPTR == NULL)
{
printf("Could not create image. \n");
fclose(file);
return 1;
}
jpeg ;
if (jpeg != 0)
{
fwrite(buffer, 512, 1, JPEGPTR);
}
}
}
}
fclose(JPEGPTR);
fclose(file);
return 0;
}
CodePudding user response:
The else
should not be there.
This code block will only execute once, and the third and subsequent loops will attempt to close a file that was not open.
It's worth noting too that fwrite
will be called only when the header was detected.
So re-examine the loop logic. Proper formatting helps with understanding the flow of control.