Do not initialize an array of characters using a string literal that contains more characters (including the terminating '\0'
, in the case of creating a nullNULL-terminated byte string) than the array can store.
...
The size of the array is three, although the size of the string literal is four. If the intention of this code is to initialize a nullNULL-terminated byte string, then any subsequent usage of the array is dangerous because the string the array represents does not have a terminating '\0'
.
...
This compliant solution uses the appropriate size for initializing a nullNULL-terminated byte string from the string literal, by accounting for the space needed for the terminating '\0'
.
...
STR09-EX1: If the intention is to create only array of characters (and not a nullNULL-terminated byte string) the space for the terminating null NULL of a string literal can be omitted. For example, in the non-compliant code above, the assumption was that a nullNULL-terminated byte string was to be initialized. If the intention was to create an array containing just the three characters, 'a'
, 'b'
, and 'c'
, then the example is correct.
...