从原始数据文件中提取 JPEG 的程序会产生分段错误(在 C 中)

program to extract JPEGs from raw data file creates segmentation fault (in C)

我是编写读取或写入文件的程序的新手,我完全不知道为什么我总是遇到分段错误。我觉得这可能与我的文件指针之一或新创建的文件有关,但非常感谢更有经验的人提供任何帮助!

另一条信息 - 当我尝试调试程序时,它似乎卡住了检查第 35 行周围的 if 语句的时间比我预期的要长,然后最终 - 分段错误。

下面是我的完整代码:

    // program to recover deleted JPEGs from memory card

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    // ensure proper usage
    if (argc != 2)
    {
        fprintf(stderr, "Usage: recover inputFile\n");
        return 1;
    }
    // remember filename
    char *infile = argv[1];

    // open input file
    FILE *inptr = fopen(infile, "r");
    if (inptr == NULL)
    {
        fprintf(stderr, "Could not open %s.\n", infile);
        return 2;
    }

// read raw input file
    int buffer[512];
    int counter = 0;
    char filename[8];
    FILE* img;

    // repeat until EOF
    while (fread (&buffer, 1, 512, inptr) == 512)
    {
        //fread (&buffer, 1, 512, inptr);  // this might be redundant (while statement)
    // check for start of JPEG
        if (buffer[0] == 0xff &&
            buffer[1] == 0xd8 &&
            buffer[2] == 0xff &&
            (buffer[3] & 0xf0) == 0xe0)
        {
            if (counter > 0) // if this is not the first jpeg found, we need to close previous jpeg
            {
                fclose(img);
            }
            // create and open file
            sprintf(filename, "%03i.jpg", counter);
            counter ++; //keep track of current jpeg count

            img = fopen(filename, "w");
            // make sure our pointer wasn't NULL
            if (img == NULL)
            {
                fprintf(stderr, "Could not open %s.\n", filename);
                return 2;
            }
            do
            {
            // Write current buffer to JPEG
            fwrite (&buffer, 512, 1, img);
            fread (&buffer, 1, 512, inptr);
            }
            // making sure to stop at start of new JPEG
            while ((buffer[0] == 0xff &&
                    buffer[1] == 0xd8 &&
                    buffer[2] == 0xff &&
                    (buffer[3] & 0xf0) == 0xe0) == 0);
            // move cursor back one 512 byte block so it can be re-read for if-statement
            fseek (inptr, -512, SEEK_CUR);
        }
    }
    // close remaining open files
    fclose(img);
    fclose(inptr);
}

当它试图关闭从未打开的 img 文件时,分段错误最终出现在程序的末尾。使用 int 而不是 unsigned char 导致 if 语句比较失败。