...
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. Subclause 6.7.9, paragraph 14, of the C Standard [ISO/AA. Bibliography#ISO-IEC 9899:-2011], says:
An array of character type may be initialized by a character string literal or UTF−8 string literal, optionally enclosed in braces. Successive bytes of the 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 BB. Definitions#vulnerability if a null-terminated byte string is assumed.
...
Code Block | ||||
---|---|---|---|---|
| ||||
const char s[3] = "abc";
| ||||
The size of the array s
is 3, although the size of the string literal is 4. 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. Do not pass a non-null-terminated character sequence to a library function that expects a string.)
...
Code Block | ||||
---|---|---|---|---|
| ||||
const char s[] = "abc";
| ||||
This approach is preferred because the size of the array can always be derived even if the size of the string literal changes.
...
Code Block | ||||||||
---|---|---|---|---|---|---|---|---|
| char s[3] = { 'a', 'b', '
| ' }; /* NOT a string */
|||||||
Also, you should make clear in comments or documentation if a character array is, in fact, not a null-terminated byte string.
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <string.h>
void func(void) {
char s[10] = "abc";
strcpy(&s[3], "def");
} | ||||
Risk Assessment
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
STR11-C | Low | Probable | Low | P6 | L2 |
...
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
|
|
| |||||||
| CC2.STR36 | Fully implemented | |||||||
CERT C Rules implemented in the LDRA tool suite |
| 404 S | Partially implemented | ||||||
PRQA QA-C |
| 1312,0690 | Partially implemented | ||||||
|
|
|
...
Bibliography
[ECTC 1998AA. Bibliography#ECTC 98] | Section A.8, "Character Array Initialization" |
[ISO/AA. Bibliography#ISO-IEC 9899:-2011] | Subclause 6.7.9, "Initialization" |
[Seacord AA. Bibliography#Seacord 2013] | Chapter 2, "Strings" |
...