C - 在 cs50 ide 中等待程序退出时超时



我正在编写一个代码,该代码从存储卡(卡.raw是我们提供的存储卡(卡(中读取信息,但代码使用用户输入(并使用jpeg的签名从中提取jpeg(0xff,0xd8,0xff,0x00 - 0xff(。我遇到了分段错误,因为我使用 malloc 哇,但我修改了我的代码并且不再使用任何 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 imagen");
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[512];
int counter = 0;
FILE *image;
char name[8];
//loop till end of file reached and read a block of input
while(fread(buff, sizeof(BYTE), 512, file) > 0)
{
//check if found jpeg
if (buff[0] == 0xff && buff[1] == 0xd8 && buff[2] == 0xff && ((buff[3] & 0xf0) == 0xe0))
{
//first jpeg
if(counter == 0)
{
sprintf(name, "%03i.jpg", counter);
image = fopen(name, "w");
fwrite(buff, sizeof(BYTE), 512, image);
counter++;
}
//jpegs after the first
else
{
fclose(image);
sprintf(name, "%03i.jpg", counter);
image = fopen(name, "W");
fwrite(buff, sizeof(BYTE), 512, image);
counter++;
}
}
else
{
fwrite(buff,sizeof(BYTE), 512, image);
}
}
fclose(image);
fclose(file);
}

IM收到的错误消息是

:) recover.c exists.
:) recover.c compiles.
:) handles lack of forensic image
:( recovers 000.jpg correctly
timed out while waiting for program to exit
:( recovers middle images correctly
timed out while waiting for program to exit
:( recovers 049.jpg correctly
timed out while waiting for program to exit

问题

  1. 正如@David拉涅利在评论中提到的,这个错别字会导致 赛格。故障。修复它。
  2. 您尝试写入而不检查图像文件是否已为此打开。我在代码中添加了else if (image != NULL)
  3. 我知道这听起来很疯狂,但变量声明的顺序很重要

此顺序会产生分段错误。

FILE *image;
char name[8];

但不是这个。

char name[8];
FILE *image;

我将对SO进行一些研究以了解这一点。欢迎任何解释。

注意;经过一些实验,我意识到当指针用NULL初始化时,顺序不会导致seg。故障了。所以最好初始化它。

最终代码(在 CS50 ide 中测试(;

#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 imagen");
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[512];
int counter = 0;
FILE *image = NULL;
char name[8];

//loop till end of file reached and read a block of input
while(fread(buff, sizeof(BYTE), 512, file) > 0)
{
//check if found jpeg
if (buff[0] == 0xff && buff[1] == 0xd8 && buff[2] == 0xff && ((buff[3] & 0xf0) == 0xe0))
{
//first jpeg
if(counter == 0)
{
sprintf(name, "%03i.jpg", counter);
image = fopen(name, "w");
fwrite(buff, sizeof(BYTE), 512, image);
counter++;
}
//jpegs after the first
else
{
fclose(image);
sprintf(name, "%03i.jpg", counter);
image = fopen(name, "w");
fwrite(buff, sizeof(BYTE), 512, image);
counter++;
}
}
else if(image != NULL)
{
fwrite(buff,sizeof(BYTE), 512, image);
}
}
fclose(image);
fclose(file);
}

最新更新