I have almost written working a recover.c. But when I want to use do while loop, memory segmentation fault appears. Of course I can write a code in a different way avoiding do while loop, but I want to understand the reason why it is not working. In my opinion code should work.

What could I improve to make it work?

That's my code:

 * recover.c
 * Computer Science 50
 * Problem Set 4
 * Recovers JPEGs from a forensic image.

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

int main(void)
    // create a 512 byte buffer
    char buffer[512];

    // first 4 bytes of jpeg
    char jpg0[4] = {0xff, 0xd8, 0xff, 0xe0};
    char jpg1[4] = {0xff, 0xd8, 0xff, 0xe1};

    //file pointers
    FILE *source;
    FILE *dest = NULL;

    char filename[8];
    int filenumber = 0;

    //open a source file
    source = fopen("card.raw", "r");

    // while next chunk of memory with size of buffer exist
    while (fread(&buffer, sizeof(buffer), 1, source))
        // if the first 4 bytes of buffer starts like JPEG
        if (memcmp(&buffer, &jpg0, 4) == 0 || memcmp(&buffer, &jpg1, 4) == 0)
            // create and name destination file inf "###.jpg" format
            sprintf(filename, "%03d.jpg", filenumber);

            // open destination file 
            dest = fopen(filename, "w");

            // write a chunk of read memory to destination file
            fwrite(&buffer, sizeof(buffer), 1, dest);
        while (memcmp(&buffer, &jpg0, 4) != 0 && memcmp(&buffer, &jpg1, 4) != 0);


    // close dest file if it was opened beofre
    if (dest != NULL)

    // that's all folks
    return 0;

1 Answer 1


Looks like your are trying to write fwrite(&buffer, sizeof(buffer), 1, dest); before dest is defined. How so? Let's assume the first read does not find a jpeg signature. What then? It enters the do/while loop, and tries to write to dest, which is undefined.

Make sure you are using the CS50x 2016 version of the specification, in which the jpeg signature is defined thus:

Specifically, the first three bytes of JPEGs are

0xff 0xd8 0xff

from first byte to third byte, left to right. The fourth byte, meanwhile, is either 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, of 0xef. Put another way, the fourth byte’s first four bits are 1110.

You must log in to answer this question.

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