No compiler error when fixed size char array is in

2019-01-04 13:32发布

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?

2条回答
Animai°情兽
2楼-- · 2019-01-04 14:18

This is expected behavior for line 6, from the draft C99 standard section 6.7.8 Initialization paragraph 14 says (emphasis mine):

An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

In the C11 draft standard the relevant section with similar wording is 6.7.9 paragraph 14, and as the C FAQ says:

The array is therefore not a true C string and cannot be used with strcpy, printf's %s format, etc.

As Keith Thompson noted, C++ is stricter, the relevant section in the draft C++ standard says the following:

There shall not be more initializers than there are array elements. [ Example:

char cv[4] = "asdf"; // error

is ill-formed since there is no space for the implied trailing ’\0’. —end example ]

查看更多
疯言疯语
3楼-- · 2019-01-04 14:23

It's legal, toosmall4 is not a string, but a valid char array(without the terminating null character).

Reference: C FAQ.

查看更多
登录 后发表回答