CS50 recover segmentation fault Oct 2020

偶尔善良 提交于 2021-01-27 19:13:00

问题


I'm new to coding and started with Harvard's CS50 course. I've written some code for recover for cs50, and tried to run it, but segmentation fault occurs.

In need of some help in identifying what's wrong.

#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;
}

回答1:


Focus on this part.

else
{
    fwrite(bytes, 512, 1, img);
}

Lets say I am reading every 512 byte in the memorycard, could not find any jpeg sign. And the code directly jumps into else statement. Lets see what is going on there.

fwrite(bytes, 512, 1, img);

img is NULL here (i.e there is no such an img file created), and fwrite intends to write on non-existing file. Bam! It is segmentation fault. If you add this condition it should be ok.

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


来源:https://stackoverflow.com/questions/64368232/cs50-recover-segmentation-fault-oct-2020

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!