...
This noncompliant 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.
Code Block | ||
---|---|---|
| ||
const char s[3] = "abc";
|
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 STR32-C. Null-terminate byte strings as required).
...
This compliant solution does not specify the bound of a character array in the array declaration. If the array bound is omitted, the compiler will allocate sufficient storage to store the entire string literal, including the terminating null character.
Code Block | ||
---|---|---|
| ||
const char s[] = "abc";
|
This is the preferred approach, because the size of the array can always be derived even if the size of the string literal changes.
...
Also, one should make clear in comments or documentation if a character array is, in fact, not a null-terminated byte string.
STR36-EX2: If the string being initialized might change in the future, one may explicitly specify an array bounds. This is particularly important if the array might hold strings longer than the initialization string.
Code Block | ||
---|---|---|
| ||
const char s[10] = "abc";
strcpy(s[4], "def");
|
Risk Assessment
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
STR36-C | high | probable | low | P18 | L1 |
...