Electric Coffee Electric Coffee - 20 days ago 5
C Question

Where is the null-character in a fixed-length empty string?

So I got curious reading some C code; let's say we have the following code:

char text[10] = "";


Where does the C compiler then put the null character?

I can think of 3 possible cases


  1. In the beginning, and then 9 characters of whatever used to be in memory

  2. In the end, so 9 characters of garbage, and then a trailing
    '\0'

  3. It fills it completely with 10
    '\0'



The question is, depending on either case, whether it's necessary to add the trailing
'\0'
when doing a
strncpy
. If it's case 2 and 3, then it's not strictly necessary, but a good idea; and if it's case 1, then it's absolutely necessary.

Which is it?

Answer

In your initialization, the text array is filled with null bytes (i.e. option #3).

char text[10] = "";

is equivalent to:

char text[10] = { '\0' };

In that the first element of text is explicitly initialized to zero and rest of them are implicitly zero initialized as required by C11, Initialization 6.7.9, 21:

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

Comments