我找不到细分错误发生的地方

时间:2020-04-01 16:08:19

标签: c segmentation-fault

我正在为我的编程班制作一个程序,其中我必须从另一个文件中恢复JPG文件并将它们存储到自己的单独文件中。该代码可以很好地编译,但是当我运行它时,我遇到了一个分段错误,而且似乎找不到它发生的地方。

    bool firstJpeg = true;
    char *jpeg;
    int jpegCount = 0;
    char *jpegName = NULL;
    FILE *newJpeg;

    // I think it's happening somewhere in the following block of code

    // read file until EOF

    while (feof(file) == false)
    {

        if (firstJpeg == true) 
        {
            if (checkJpeg(file)) 
            {
                fseek(file, -4, SEEK_CUR); //brings cursor back 4 bytes
                firstJpeg = false;
                jpegCount++;
                sprintf(jpegName, "00%d.jpg", jpegCount); // makes a name for the new jpeg file
                puts(jpegName);
                newJpeg = fopen(jpegName, "w"); // opens new jpeg file
                jpeg = malloc(sizeof(char) * 512); // allocates 512 bytes
                fread(jpeg, 512, 1, file); // reads 512 bytes
                fwrite(jpeg, 512, 1, newJpeg); // writes 512 bytes into the new jpeg file

            }
            else
            {
                fseek(file, 508, SEEK_CUR); // skips the next 508 bytes
            }
        }

0 个答案:

没有答案