0

This has me confused.

In the following code, I create an array of characters initialized at size 7. The array needs to store at least 6 characters, so I've made it large enough to do that (I think?). Then with the next line of code I put the string "000.jpg" into that array. Then I write data into a file with that string as its name. The program works fine and all files are named correctly.

        //create a string for the name of the new jpg
        char filename[7];

        //name the new jpg according to the current file number
        sprintf(filename, "%03i.jpg", file_number);

        //open new jpg file
        photo = fopen(filename, "w");

        //write first bloc of new jpg
        fwrite(buffer, sizeof(unsigned char), 512, photo);

But then I changed this line to:

    //create a string for the name of the new jpg
    char filename[2];

and the files are still named correctly. So my question is why?

If an array is a fixed size, why can I store then entire file name in it if it's more than 3 characters?

I'm happy to share the rest of the program if it helps. thanks!

1

First of all, to store "000.jpg", the array size needs to be 8, not 7. You MUST leave room for the end of string marker, '\0'.

It works, partly because you've just been lucky. Even though the array is allocated to a specific size, whether it's 8, or 7 or 2, C will allow a write to that location to be executed no matter how much data is written. (It goes back to historical concepts that allow consecutive strings to be written and changed, and then to be treated as one long string.)

As a practical matter, here's what happens. If you write a short string to a longer storage location or array, no problem. The unused space won't be changed. The problem happens come when you try to write a long string to a short space. C will do it!

Say that you have a variable like this:

char mystring[10];

Now, later, you execute this:

strcpy(mystring, "this string is too long!");

Well, C will obediently write the entire string into physical memory using the starting address of mystring. Unfortunately, it will overwrite the physical memory that follows. If that overwritten memory hasn't been allocated, or if that memory is reloaded afterwards, you'll luck out and it'll work. But, if the code needs to retrieve data from that overwritten memory after the string write, it's corrupted and results become unpredictable.

So, it's critical to make sure that when a string is written to memory, it doesn't exceed the space allocated. If it does, data may or may not get corrupted, so results are unpredictable.

Any questions?

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • Thank you for your answer. That's a great look into how memory works! – WhatEvenIsCoding Jan 29 at 2:23

You must log in to answer this question.

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