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

int main(int argc, char *argv[])
{
// check arguments
if (argc != 2)
{
    fprintf(stderr, "USAGE: ./recover raw_file\n");
    return 1;
}

FILE *card = fopen(argv[1], "r");

// check whether the pointer equals to null
if (card == NULL)
{
    fprintf(stderr, "could not open file\n");
    return 2;
}

uint8_t buffer[512];
int tracker = 0;
char filename[3];
FILE *img;

while (fread(buffer, 512, 1, card) == 1)
{

// check if that is the start of a JPEG
    if(buffer[0] == 0xff &&
    buffer[1] == 0xd8 &&
    buffer[2] == 0xff &&
    (buffer[3] & 0xf0) == 0xe0)
    {
        if (tracker -1 > 0)
        {
            fclose(img);
            tracker++;
        }
        // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        sprintf(filename, "%03i.jpg", tracker);
        tracker++;


        img = fopen(filename, "w");
        if (img == NULL)
        {
            fprintf(stderr, "could not open\n");
            return 3;
        }

        fwrite(buffer, 512, 1, img);

        continue;

    }

    if (tracker -1 >= 0)
    {
        fwrite(buffer, 512, 1, img);
    }

}

fclose(card);
return 0;
}

I don't know why "tracker" after sprintf get big values like 17323892 and 8321421 or similar. What is the problem here? Thanks for any help.

1

Your file name is 7 characters long, so plus the null terminator, your filename variable should point to a memory block of at least 8 characters, not 3.

What happens is that sprintf prints to memory that does not belong to filename any more (as it's beyond the 3-character range for string including null-terminator), so probably tracker in this case.

3
  • why should filename variable point to a memory block of at least 8 characters? – SamGal May 30 '17 at 14:39
  • 1
    3 digits + period + file extension + null terminator = 8. For example, with "001.jpg", you have 7 characters, but since strings require null-termination, you can't use just 7 but need to make room for 8. – Peter May 30 '17 at 15:55
  • oh, I haven't noticed that, thanks. – SamGal May 30 '17 at 16:21

You must log in to answer this question.

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