0

My program compiles, but when I run it I get a segmentation fault and nothing else:

    ~/workspace/recover/ $ make recover
    clang -fsanitize=integer -fsanitize=undefined -ggdb3 -O0 -std=c11 -Wall 
    -Werror -Wextra -Wno-sign-compare -Wshadow    recover.c  -lcrypt -lcs50 
    -lm -o recover
    ~/workspace/recover/ $ ./recover card.raw
    Segmentation fault
    ~/workspace/recover/ $ 

Here is my code:

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

    typedef uint8_t BYTE;

    int main(int argc, char *argv[])
    {
int jpg_ctr = 0;
// ensure proper usage
if (argc != 2)
{
    fprintf(stderr, "Usage: ./recover jpeg\n");
    return 1;
}

// remember filenames
char *pfile_n = argv[1];

// open input file
FILE *pfile = fopen(pfile_n, "r");
if (pfile == NULL)
{
    fprintf(stderr, "Could not open %s.\n", pfile_n);
    return 2;
}
BYTE iter[512];
FILE *jpeg = NULL;
char jpegn[16];

while (!feof(pfile))
{
    if (iter[0] == 0xff && iter[1] == 0xd8 && iter[2] == 0xff && (iter[3] & 0xf0) == 0xe0)
    {
        if (jpg_ctr > 0)
        {
            fclose(jpeg);
        }
        jpg_ctr++;
        sprintf(jpegn, "%03d.jpg", jpg_ctr);
        fwrite(iter, sizeof(iter), 1, jpeg);
        jpeg = fopen(jpegn, "w");
    }
    if (jpg_ctr > 0)
    {
        fwrite(iter, sizeof(iter), 1, jpeg);
    }
    fread(iter, sizeof(iter), 1, pfile);
}

// close infile
fclose(pfile);

// success
return 0;
}

Sorry for the poor formatting!

1

The first step is to identify which line is triggering the seg fault.

When the code writes to the output file, has the file been opened yet?

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance.

| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .