0

My code:

//create space save info from card
unsigned char buffer[512];
int jpgCount = 0;
char title[7];
do
{
    if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff)
    {
        sprintf(title, "00%i.jpg", jpgCount);
        FILE* img = fopen(title,"a");
        printf("This is the start of a jpg file! This is JPG number: %i \n",jpgCount);
        fclose(img);
        jpgCount++;
    }
}
while (fread(buffer, 512, 1, file) == 1);

fclose(file);

return 0;

}

The outcome is not what I expected though.The program correctly identifies the jpgs 50 times, printing out"This is the start of a jpg file! This is JPG number: 0 " 50 times! Why doesn't the variable add up? Also, only one file is opened. What am I missing that's messing this while loop up?

Appreciate your help!

1 Answer 1

0

Welcome to the wonderful, wacky, wtf world of memory leak! This allocation char title[7]; is causing the problem. This sprintf(title, "00%i.jpg", jpgCount); is stomping on jpgCount's memory. How so? Let's take i = 0. sprintf will create title as 001.jpg. Which is 7 chars. But wait, there's more! Where's it going to put the null terminator (and it will add a null terminator)? It will put the null terminator in memory it doesn't own, which in this case belongs to jpgCount.

Take it for a spin in gdb. Inspect jpgCount after sprintf(title, "00%i.jpg", jpgCount); executes to get a visual.

Once you fix the allocation, you will still have a problem because of the format string "00%i.jpg". The format string "%03i.jpg" would work. format strings are like their own language, I have found this article useful. Or try "printf leading 0" in your favorite search engine.

Only one file is opened because you are using "a"ppend mode. More info here.

You must log in to answer this question.

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