[英]I am getting a segmentation fault in my code
我正在編寫一個代碼,該代碼從 memory 卡中讀取信息(card.raw 是我們提供的,但代碼使用用戶輸入)並使用 jpeg 具有的簽名(0xff,0xd8,0xff,0x00)從中提取 jpeg - 0xff)。 我遇到了分段錯誤,因為我使用的是 malloc,但我看不出哪里出錯了。 我在這里粘貼我的代碼,任何幫助將不勝感激。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
//check terminal usage
if (argc != 2)
{
printf("Usage: ./recover image");
return 1;
}
//open inputted file and check for valid file
FILE *file = fopen(argv[1], "r");
if (!file)
{
printf("Invalid or missing file.");
return 1;
}
BYTE *buff = malloc(512 * sizeof(BYTE));
int counter = 0;
FILE *image = NULL;
char *name = malloc(8 * sizeof(char));
//loop till end of file reached and read a block of input
while(fread(buff, sizeof(BYTE), 512, file) == 1 && !feof(file))
{
bool foundJPEG = buff[0] == 0xff && buff[1] == 0xd8 && buff[2] == 0xff && ((buff[3] & 0xf0) == 0xe0);
//check if found jpeg, and open file for writing
if (foundJPEG)
{
sprintf(name, "%03i.jpg", counter);
image = fopen(name, "w");
}
//if image file open, write to it
if (image != NULL)
{
fwrite(buff, sizeof(BYTE), 512, image);
}
//if found a jpeg already, close it so new one can be written
if (foundJPEG && image != NULL)
{
fclose(image);
counter++;
}
}
free(name);
free(buff);
fclose(image);
fclose(file);
return 0;
}
上面的代碼存在三個問題,注釋中沒有提到:
讀取成功后, fread
的返回值不是 1 而是 512。 您交換了 blocksize 和 blockcount -> fread 定義的參數。 因此不進入while循環。 不要試圖通過將大量代碼打包到一個語句中來節省空間。 如果將fread
返回值和 EOF 的檢查分開並使用do... while()
循環會更聰明。 然后你有機會在調試器中看到這個問題。 這正是我所做的以及我是如何發現這一點的。
第二個問題是您在搶救前 512 個字節后關閉了圖像,但您沒有將文件指針image
重置回NULL
以及fclose
語句。 結果,代碼將重復寫入一個關閉的文件,直到找到一個帶有 jpg header 的新塊。
第三個問題是你只拯救了 jpg 的前 512 個字節,而不是整個 jpg。 您需要掃描輸入 stream 以查找 jpg 結束指示符FF D9
並復制字節,直到找到為止。 -> jpg 格式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.