I am getting a segmentation error when I run recover. I've looked at other questions regarding segmentation errors but cant find the issue. Below is my code. Thanks!

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

typedef uint8_t  BYTE;

int BLOCKSIZE = 512;

int main(int argc, char *argv[])
    // Ensure proper usage, there should be 2 arguments
    if (argc != 2)
        printf("Usage: Name of a forensic image from which to recover JPEGs\n");
        return 1;

    // Remember the file names as string
    char *infile = argv[1];

    // Open the input file as read only by getting address of infile
    FILE *inptr = fopen(infile, "r");
    if (inptr == NULL)
        printf("Could not open file%s.\n", infile);
        return 2;

    //Referenced https://cs50.stackexchange.com/questions/25465/am-i-using-sprintf-correctly/25469
    // to see how to declare filename
    BYTE buffer[BLOCKSIZE];
    int counter = 0;
    while (fread(buffer, 1, BLOCKSIZE, inptr) == BLOCKSIZE)
        char filename[8];
        FILE *img = NULL;
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
            fseek(img, 0, SEEK_END);
            if (ftell(img) == 0)
            sprintf(filename, "%03i.jpg", counter);
            img = fopen(filename, "w");
            fwrite(buffer, 1, BLOCKSIZE, img);

fclose(img); what happens if there is no open image? You will segfault. You should never call fclose unless you first confirm that a file is open (ie, by checking that img isn't null).

edit You are also calling fseek on img without checking it exists. I'm not sure why you you do that, unless it's to check if it actually is open. You can simply say if (img) { to do that.

  • I tried using if (img != NULL) { fclose(img); } But that got me error in `./recover': munmap_chunk(): invalid pointer: 0x00007ffcc8465bb0 ***. Hmmm
    – Roseyrat
    Oct 3 '18 at 0:46
  • @Roseyrat : Before you get to the fclose(img), you already do a fseek(img, 0, SEEK_END);. You can only do that after you have opened that file ... So again, you should check that imgisn't null before doing that, just like @curiouswiki already told you. Oct 3 '18 at 8:35

You must log in to answer this question.

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