Do not initialize an array of characters using a string literal with more characters (including the '\0') than the array. Consequently, it is necessary to specify the correct size of a string literal.
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.
char s[3] = "abc"; |
The size of the array is three, although the size of the string literal is 4.
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,
char s[4] = "abc"; |
This compliant solution uses the the initialization method of not describing the size.
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.
Recommendation |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
|---|---|---|---|---|---|
STR09-A |
high |
probable |
medium |
P12 |
L1 |
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
\[[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 |
STR06-A. Do not assume that strtok() leaves the parse string unchanged 07. Characters and Strings (STR)