csegmentation-faultcs50

My c code is giving unknown segmentation fault


So I am doing the CS50 practice problem of week 4. It's about recovering a JPEG file that has been deleted so you enter the file check for 4 headers (first 3 the same and the 4th can vary but they gave you a solution) but the program is giving me a segmentation fault and I spend so much time debugging but still can't figure it out. I'm new and any help is appreciated

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

typedef uint8_t BYTE;

int main(int argc, char *argv[])
{
    //check for 2 command-line arguments
    if (argc != 2)
    {
        printf("Input one command-line argument\n");
        return 1;
    }

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

    //the first 4 bytes which are the headers
    BYTE b[4];
    int filecounter = 0;

    //a line to check that I'm still not at the end of the file
    while (fread(&b, sizeof(b), sizeof(b), f) == sizeof(b))
    {
        if (b[0] == 0xff && b[1] == 0xd8 && b[2] == 0xff && (b[3] & 0xf0) == 0xe0)
        {
            filecounter++;

            char filename[10];
            sprintf(filename, "%03i.jpg", filecounter);

            FILE *img = fopen(filename, "w");

            BYTE BLOCK[512];

            //Same checking for end of File
            if (fread(&BLOCK, sizeof(BLOCK), sizeof(BLOCK), f) != sizeof(BLOCK))
            {
                fclose(img);
                fclose(f);
                return 1;
            }

            fwrite(&BLOCK, 512, 512, img);
            fclose(img);
        }
    }

    fclose(f);
    return 0;
}

I tried debugging on multiple lines of code but ended up having to remove most of the program for it to stop giving segmentation fault so I couldn't really check where the error is.


Solution

  • I believe that segmentation fault source is in while (fread(&b, sizeof(b), sizeof(b), f) == sizeof(b)) you used & in the wrong place.
    The function you should use is size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream).
    It will get the reference of the variable as it do.