Suppose I have the following c char arrays:
char okaysize4[5] = "four"; // line 5
char toosmall4[4] = "four"; // line 6
char toosmall3[3] = "four"; // line 7
When I compile with gcc 4.4.7, I get the following error:
array.c:7: warning: initializer-string for array of chars is too long
This error is expected for line 7, as I am trying to stuff 5 chars ("four" + \0)
into a 3 element array.
Also no error is expected for line 5 as the 5 element array is big enough.
However I'm surprised there is no similar error for line 6. What ends up getting initialized in toosmall4
is an unterminated string, which can cause all sorts of trouble.
My understanding is that the c string literal "four"
should be five characters long, due to the null terminator. In fact sizeof("four")
is 5. So why does the compiler not give an error here?
Is there some way I can alter my declaration/definition/initialization so that an error is flagged in this case?
This is expected behavior for line 6, from the draft C99 standard section
6.7.8
Initialization paragraph 14 says (emphasis mine):In the C11 draft standard the relevant section with similar wording is
6.7.9
paragraph 14, and as the C FAQ says:As Keith Thompson noted, C++ is stricter, the relevant section in the draft C++ standard says the following:
It's legal,
toosmall4
is not a string, but a valid char array(without the terminating null character).Reference: C FAQ.