所以這個程式嘗試使用 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, "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;
}
uj5u.com熱心網友回復:
else不應該在那里。
此代碼塊只會執行一次,第三次及后續回圈將嘗試關閉未打開的檔案。
值得注意的是,fwrite只有在檢測到標頭時才會呼叫它。
所以重新檢查回圈邏輯。正確的格式有助于理解控制流程。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/465487.html
下一篇:帶有指標和記憶體說明的行內代碼
