Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Do not initialize an array of characters using a string literal with that contains more characters (including the terminating '\0') than the array. Consequently, it is necessary to specify the correct size of a string literal, in the case of creating a null-terminated byte string) than the array can store.

Non-Compliant Code Example

...

The size of the array is three, although the size of the string literal is 4four. If the intention of this code is to initialize a null-terminated byte string, then any subsequent usage of the array is dangerous because the string the array represents does not have a terminating '\0'.

Compliant Solution

This compliant solution uses the the initialization method of not describing the size, because the result of the expectation always can be obtained even if the size of the string literal is changed, appropriate size for initializing a null-terminated byte string from the string literal, by accounting for the space needed for the terminating '\0'.

Code Block
bgColor#ccccff
char s[4] = "abc";

...

This compliant solution uses the the array initialization method of not describing the sizewhich does not explicitly describe the size. By omitting the size, the array will automatically be of appropriate length to store the full string literal.

Code Block
bgColor#ccccff
char s[] = "abc";

This is the preferred approach, because the result of the expectation always can be obtained even if the size of the string literal is changed.

Exceptions

STR09-EX1: If the intention is to create only array of characters (and not a null-terminated byte string) the space for the terminating null of a string literal can be omitted. For example, in the non-compliant code above, the assumption was that a null-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.

Risk Assessment

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

STR09-A

high

probable

medium

P12

L1

...