Do not initialize The C standard allows an array of characters to be initialized using a string literal that contains more characters (including the terminating '\0'
, in the case of creating fits exactly in the array, not counting the terminating null character. However, this has limited utility and the potential to cause vulnerabilities when a null-terminated byte string ) than the array can storeis assumed. Consequently, this practice is disallowed by this standard. A better approach is to not specify the dimension of a character array initialized with a string literal, as the compiler will automatically allocate sufficient space for the entire string literal, including the terminating null character.
Non-Compliant Code Example
This non-compliant code example initializes an array of characters using a string literal that defines one more character (counting the terminating '\0'
) than the array can hold.
...
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 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 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 | ||
---|---|---|
| ||
char s[4] = "abc"; |
Compliant Solution
This compliant solution uses the array initialization method which does not explicitly describe the size. By omitting the size, the array will automatically be of appropriate length to store the full string literal.
...
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
STR09STR36-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 STR36-A C | high | probable | medium | P12 | L1 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] \[[Seacord 05a|AA. C References#Seacord 05a]\] Chapter 2, "Strings" [The Embedded C++ Programming Guide Lines|http://www.caravan.net/ec2plus/guide.html]. Version WP-GU-003. 6,Jan 1998 by the Embedded C++ Technical Committee A.8 Character array initialization |
...