【发布时间】:2020-12-09 09:18:54
【问题描述】:
我正在尝试编写一个程序,该程序将从文件中恢复已删除的图像并将这些图像中的每一个写入它们自己的单独文件中。我已经被这个问题困扰了几天,并尽我所能自己解决它,但我现在意识到我需要一些指导。我的代码总是编译得很好,但是每次我运行我的程序时都会遇到分段错误。使用 valgrind 表明我没有任何内存泄漏。
我想我已经查明了问题所在,但我不确定如何解决。当我通过调试器运行我的程序时,它总是停在我最后一个“else”条件内的代码处(其中注释说“如果已经找到 JPEG”),并给我一条关于分段错误的错误消息。
我已经尝试在这行代码顶部打开并初始化我的文件指针 jpegn,以防止 jpegn 在运行此条件时为 NULL,但这并不能修复故障。
我对编程(和这个网站)非常陌生,所以任何建议或建议都会有所帮助。
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
if(argc!=2) // Checks if the user typed in exactly 1 command-line argument
{
printf("Usage: ./recover image\n");
return 1;
}
if(fopen(argv[1],"r") == NULL) // Checks if the image can be opened for reading
{
printf("This image cannot be opened for reading\n");
return 1;
}
FILE *forensic_image = fopen(argv[1],"r"); // Opens the image inputted and stores it in a new file
BYTE *buffer = malloc(512 * sizeof(BYTE)); // Dynamically creates an array capable of holding 512 bytes of data
if(malloc(512*sizeof(BYTE)) == NULL) // Checks if there is enough memory in the system
{
printf("System error\n");
return 1;
}
// Creates a counting variable, a string and two file pointers
int JPEG_num=0;
char *filename = NULL;
FILE *jpeg0 = NULL;
FILE *jpegn = NULL;
while(!feof(forensic_image)) // Repeat until end of image
{
fread(buffer, sizeof(BYTE), 512, forensic_image); // Read 512 bytes of data from the image into a buffer
// Check for the start of a new JPEG file
if(buffer[0] == 0xff & buffer[1] == 0xd8 & buffer[2] == 0xff & (buffer[3] & 0xf0) == 0xe0)
{
// If first JPEG
if(JPEG_num == 0)
{
sprintf(filename, "%03i.jpg", JPEG_num);
jpeg0 = fopen(filename, "w");
fwrite(buffer, sizeof(BYTE), 512, jpeg0);
}
else // If not first JPEG
{
fclose(jpeg0);
JPEG_num++;
sprintf(filename, "%03i.jpg", JPEG_num);
jpegn = fopen(filename, "w");
fwrite(buffer, sizeof(BYTE), 512, jpegn);
}
}
else // If already found JPEG
{
fwrite(buffer, sizeof(BYTE), 512, jpegn);
}
}
// Close remaining files and free dynamically allocated memory
fclose(jpegn);
free(buffer);
}
【问题讨论】:
-
关于:
if(JPEG_num == 0) { sprintf(filename, "%03i.jpg", JPEG_num); jpeg0 = fopen(filename, "w"); fwrite(buffer, sizeof(BYTE), 512, jpeg0); }这无法增加JPEG_num,因此执行将永远不会到达else代码块
标签: c segmentation-fault cs50