Can find out what i'm doing wrong.. Compiling seems to work, running the program gives a segmentation fault core dumped error.

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

unsigned char buffer[512]; //create buffer space to save read part of 512 bytes by fread
int firstfound = 0; //set 0 for not found yet
int num_found = 0; //how many jpg found
char startcheck1[4] = {0xff, 0xd8, 0xff, 0xe0}; //posible start of jpg
char startcheck2[4] = {0xff, 0xd8, 0xff, 0xe1}; //posible start of jpg
FILE * img = NULL;
char * filename;

int main()
    FILE * inptr = fopen("card.raw", "r"); //create infile pointer to read

    while(fread(buffer, sizeof(char), 512, inptr) == 512) //as long as we can still read 512 bytes
        // fread(&buffer, sizeof(char), 512, inptr); // read them 512 bytes
        if (buffer[0] == startcheck1[0] && buffer[1] == startcheck1[1] && buffer[2] == startcheck1[2] 
            && (buffer[3] == startcheck1[3] || buffer[3] == startcheck2[3])) // if beginning of jpg
            fclose(img); // close current file
            num_found++; //increment number found by 1
            firstfound = 1; // make true
            sprintf(filename, "%.3d.jpg", (num_found - 1)); //prints new name to filename
            FILE * img = fopen(filename, "a"); // create file pointer that points to filename and opens that file pointed to
            fwrite(buffer, sizeof(char), 512, img); // write buffer to file that file pointer points to
            if(firstfound == 1) //if first start already found
                fwrite(buffer, sizeof(char), 512, img); //write buffer

    return 0;

2 Answers 2


The program tries to reference a null pointer, img, when it encounters the first image. Since img is initialized to NULL, the first time if (buffer[0] == startcheck1[0] ....) evaluates to true, fclose(img); will cause a segfault. Try using a null check:
if(img != NULL) fclose(img);


The problem maybe in char* filename; You'd better allocate some bytes to make the filename no longer than ###.jpg

You must log in to answer this question.

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