所以这个程序尝试使用 fread() 和 fwrite() 来恢复一些已删除的 JPEG 图像的文件数据。通过我的代码,我似乎找不到错误,但是当我使用原始数据文件运行程序时,我收到错误“free(): double free detected in tcache 2 Aborted (core dumped)”
在网上看,这似乎是一个内存分配/释放问题,其中一些内存被多次释放,但我看不出这是如何完成的。
任何帮助将非常感激!
这是我的代码:
#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, "%03i.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;
}
else
不应该在那里。
此代码块只会执行一次,第三次和后续循环将尝试关闭未打开的文件。
值得注意的是,fwrite
只有在检测到标头时才会调用它。
所以重新检查循环逻辑。正确的格式有助于理解控制流程。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句