...
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.
However, if the array string is intended to be used as a null-terminated byte string, then the array will have one too few characters to hold the string because it does not account for the terminating null character. Such a sequence of characters has limited utility and has the potential to cause vulnerabilities if a null-terminated byte string is assumed.
A better approach is to not specify the bound of an array a string initialized with a string literal because the compiler will automatically allocate sufficient space for the entire string literal, including the terminating null character. This rule is a specific exception to recommendation ARR02-C. Explicitly specify array bounds, even if implicitly defined by an initializer.
...
The size of the array s
is three, although the size of the string literal is four. Any subsequent use of the array as a null-terminated byte string can result in a vulnerability, because s
is not properly null-terminated. (See rule STR32-C. Null-terminate byte strings as required.)
Implementation Details
...
STR36-EX1: If the intention is to create a character array and not a null-terminated byte string, initializing to fit exactly without a null byte is allowed but not recommended. The preferred approach to create an array containing just the three characters, 'a'
, 'b'
, and 'c'
, for example, is to declare each character literal as a separate element as follows:
...
Also, you should make clear in comments or documentation if a character array is, in fact, not a null-terminated byte string.
STR36-EX2: If the char array must be larger than the string literal it is initialized with, you may explicitly specify an array bounds. This is particularly important if the array's contents might change during program execution.
...