I can't understand why my code is giving segmentation fault. It seems alright to me. Would be great if somebody could point out the error to me.

Tried debug50 but not able to understand what is fault in the code

* Recover JPEG from a memory card

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

int main(void)

// remember filenames
char *infile = "card.raw";

// open input file 
FILE *inptr = fopen(infile, "r");
if (inptr == NULL)
    fprintf(stderr, "Could not open %s.\n", infile);
    return 1;

//define block of memory for copying stuff
uint8_t chunk[512];

/*  1. copy a chunk of memory into the variable defined
    2. check whether it is new file or part of an old file
    3. if new file then check if a jpg is open and if not then open one with a new name and if new then open a new one with a new name
    4. append the chunk to file so opened
    5. move to another chunk of memory
    6. repeat steps 1 to 5 till the end of file is not reached */

int counter = 0;
//define memory for a new name

FILE *outptr= NULL; 

while(fread(&chunk, 1, 512, inptr))

    //Step 2
    if (chunk[0] == 0xff && chunk[1] == 0xd8 && chunk[2] == 0xff
        && (chunk[3] == 0xe0 || chunk[3] == 0xe1))
        //Step 3
        // close any already opened file
        if(outptr != NULL)

        //open a new file
        char outfile[8];
        sprintf(outfile, "%03d.jpg", counter);
        counter= counter +1;

        outptr = fopen(outfile,"w");



if (outptr != NULL)


// success
return 0;


1 Answer 1


It's probably safe to assume the first block is not a jpg sig otherwise what would be the point of the exercise? At the first fread, what happens if it doesn't find a jpg sig? Control goes here fwrite(&chunk,1,512,outptr);. What is outptr? It is NULL. Program cannot write to NULL. It gives seg fault. You'll need to add logic to only write data when you are processing a jpg and have a valid outptr.

Also, make sure you are using the current version of the spec. Here is how the fourth byte is defined therein:

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.

  • 1
    Also I'd suggest replacing (chunk[3] == 0xe0 || chunk[3] == 0xe1) with (chunk[3] & 0xf0 == 0xe0), which masks away the last four bits using bitwise AND (&), as all values from 0xe0 to 0xef are valid for an APPn marker.
    – Blauelf
    Jan 31, 2017 at 15:21
  • Thanks DinoCoder and Blauelf for your help Feb 1, 2017 at 7:12

You must log in to answer this question.

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