...
It is common for an array variable to be initialized by a string literal and declared with an explicit bound that matches the number of characters in the string literal. C99, Section 6.7.8, "Initialization", paragraph 14, says:
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 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 a string initialized with a string literal , as 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 guideline 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 See guideline STR32-C. Null-terminate byte strings as required.).
Implementation Details
This code produces a compilation error in MSVC 2008.
...
This is the preferred approach , because the size of the array can always be derived even if the size of the string literal changes.
...
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
STR36-C | high | probable | low | P18 | L1 |
Automated Detection
Tool | Version | Checker | Description | ||||
---|---|---|---|---|---|---|---|
|
|
...
|
|
| |||
|
...
|
|
|
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Other Languages
Related Guidelines
This rule appears in the C++ Secure Coding Standard as : STR36-CPP. Do not specify the bound of a character array initialized with a string literal.
Bibliography
Wiki Markup |
---|
\[[ECTC 981998|AA. Bibliography#ECTC 98]\] A.8, "Character array initialization" \[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] Section 6.7.8, "Initialization" \[[ISO/IEC PDTR 24772|AA. Bibliography#ISO/IEC PDTR 24772]\] "CJM String Termination" \[[Seacord 05a2005a|AA. Bibliography#Seacord 05a]\] Chapter 2, "Strings" |
...