CS50 pset4恢复分段错误

时间:2020-06-29 16:39:37

标签: c segmentation-fault cs50

编译并运行程序时,出现分段错误。 Valgrind没有任何问题。有什么想法吗? 我疯了想找出问题所在。

程序的目的是从名为card.raw的“取证图像”中恢复JPEG。当我在代码上运行check50时,由于段错误,程序无法满足要求。

这是我的代码:

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


int main(int argc, char *argv[])
{
int jpeg_count = 0;

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

FILE *original;
original = fopen(argv[1], "r");

if(original == NULL)
{
    printf("Error! Cannot open file.\n");
    return(1);
}

unsigned char buffer[512];
char *filename = malloc(8);
fread(buffer, sizeof(buffer), 512, original);

FILE *img; 

while(1)
{
    if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] &0xf0) == 0xe0)
    {
        if(jpeg_count == 0)
        {
            sprintf(filename, "%03i.jpg", 0);
            img = fopen(filename, "w");
            fwrite(buffer, sizeof(buffer), 512, img);
            jpeg_count++;
        }
        else if(jpeg_count > 0)
        {
            fclose(img);
            sprintf(filename, "%03i.jpg", jpeg_count);
            img = fopen(filename, "w");
            fwrite(buffer, sizeof(buffer), 512, img);
            jpeg_count++;
        }
    
    }
    if(feof(original))
    {
        fclose(img);
        fclose(original);
        free(filename);
        break;
            
    }             
}

}

0 个答案:

没有答案