CS50 恢复分段错误 2020 年 10 月

CS50 recover segmentation fault Oct 2020

我是编码新手,刚开始学习哈佛的 CS50 课程。我已经为 cs50 编写了一些恢复代码,并尝试 运行 它,但是出现分段错误。

需要一些帮助来确定问题所在。

#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 语句。让我们看看那里发生了什么。

fwrite(bytes, 512, 1, img);

img 在这里是 NULL(即没有创建这样的 img 文件),fwrite 打算写入 non-existing 文件。砰!这是分段错误。如果加上这个条件应该就可以了

    else if (img != NULL)
    {
        // Write the data to a new jpeg file.
        fwrite(bytes, 512, 1, img);
    }