CS50恢复分段错误2020年10月 [英] CS50 recover segmentation fault Oct 2020
问题描述
我是编码的新手,从哈佛的CS50课程开始.我已经写了一些用于CS50恢复的代码,并尝试运行它,但是出现了分段错误.
I'm new to coding and started with Harvard's CS50 course. I've written some code for recover for cs50, and tried to run it, but segmentation fault occurs.
需要一些帮助来确定问题所在.
In need of some help in identifying what's wrong.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: ./recover image\n");
return 1;
}
FILE *file = fopen(argv[1], "r");
if (file == NULL)
{
printf("Usage: ./recover image\n");
}
char filename[8];
FILE *img = NULL;
BYTE bytes[512];
int counter = 0;
while (fread(bytes, 512, 1, file) == 1)
{
if(bytes[0] == 0xff && bytes[1] == 0xd8 && bytes[2] == 0xff && (bytes[3] & 0xf0) == 0xe0 )
{
if (counter > 0)
{
fclose(img);
}
sprintf(filename, "%03i.jpg", counter);
img = fopen(filename, "w");
fwrite(bytes, 512, 1, img);
counter++;
}
else
{
fwrite(bytes, 512, 1, img);
}
}
if (img == NULL)
fclose(img);
if (file == NULL)
fclose(file);
return 0;
}
推荐答案
此部分为重点.
else
{
fwrite(bytes, 512, 1, img);
}
可以说我正在读取存储卡中的每个512字节,找不到任何jpeg符号.然后代码直接跳转到 else
语句中.让我们看看那里发生了什么.
Lets say I am reading every 512 byte in the memorycard, could not find any jpeg sign. And the code directly jumps into else
statement. Lets see what is going on there.
fwrite(bytes, 512, 1, img);
此处
img为 NULL (即未创建此类img文件),并且fwrite打算在不存在的文件上进行写操作.am!这是分段错误.如果添加此条件,那应该没问题.
img is NULL here (i.e there is no such an img file created), and fwrite intends to write on non-existing file. Bam! It is segmentation fault. If you add this condition it should be ok.
else if (img != NULL)
{
// Write the data to a new jpeg file.
fwrite(bytes, 512, 1, img);
}
这篇关于CS50恢复分段错误2020年10月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!