CS50 pset4 恢复,出现分段错误

Posted

技术标签:

【中文标题】CS50 pset4 恢复,出现分段错误【英文标题】:CS50 pset4 Recover, got a segmentation error 【发布时间】:2020-08-02 02:34:47 【问题描述】:

此代码出现分段错误。任何人都可以帮忙吗?我尝试了几种方法,但仍然无法解决问题。我尝试用FILE *img 替换FILE *img = NULL,但它给出了另一个错误variable 'img' is uninitialized when used in fwrite(buffer, 512, 1, img)

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

int main(int argc, char *argv[])

    //Open memory card
    if (argc != 2)
    
        printf("Usage: ./recover image\n");
        return 1;
    

    FILE *file = fopen(argv[1], "r");
    if (!file)
    
        return 1;
    

    //Read 512 bytes into a buffer
    int counter = 0;
    unsigned char buffer[512];
    char filename[8];
    FILE *img = NULL;

    while (fread(buffer, 512, 1, file) == 1)
    
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] && 0xf0 == 0xe0))
        
            //If first JPEG
            if (counter == 0)
            
                //open a new file
                sprintf(filename, "%03i.jpg", counter);
                img = fopen(filename, "w");

                //write the array into the new file
                fwrite(buffer, 512, 1, img);
                counter++;
            

            //if not first JPEG
            else
            
                //close the file
                fclose(img);

                //open a new file
                sprintf(filename, "%03i.jpg", counter);
                img = fopen(filename, "w");

                //write the array into the new file
                fwrite(buffer, 512, 1, img);
                counter++;
            
        
        //Else, if already found new JPEG
        else
        
            fwrite(buffer, 512, 1, img);
        
    

    //Close any remaining files
    fclose(img);
    fclose(file);

    return 0;

【问题讨论】:

【参考方案1】:

当这个if (buffer[0] == 0xff &amp;&amp; buffer[1] == 0xd8 &amp;&amp; buffer[2] == 0xff &amp;&amp; (buffer[3] &amp;&amp; 0xf0 == 0xe0))为真(与第一次读取一样)时,程序会做什么?

这条评论//Else, if already found new JPEG需要放入代码中;即以下write 需要有条件。

【讨论】:

以上是关于CS50 pset4 恢复,出现分段错误的主要内容,如果未能解决你的问题,请参考以下文章

CS50恢复分段故障问题

CS50 PSet 2:Vigenere 密码分段错误

CS50 Speller 中的分段错误。为啥?

CS50 Pset4 过滤器(不太舒服)模糊功能算法问题

CS50 pset4 调整大小不太舒服。标题似乎已正确更新,直到我写在文件上

这段代码一次执行良好,另一次出现分段错误