Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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
bgColor#FFCCCC
langc
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 rule 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
bgColor#ccccff
langc
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.

...

STR36-EX1: If the intention is to create a character array and not a null-terminated byte string, initializing to fit exactly without a null byte is allowed but not recommended. The preferred approach to create an array containing just the three characters, 'a', 'b', and 'c', for example, is to declare each character literal as a separate element as follows:

Code Block
bgColor#ccccff
langc
char s[3] = { 'a', 'b', 'c' }; /* NOT a string */

...

STR36-EX2: If the char array must be larger than the string literal it is initialized with, you may explicitly specify an array bounds. This is particularly important if the array's contents might change during program execution.

Code Block
bgColor#ccccff
langc
char s[10] = "abc";
strcpy(&s[3], "def");

...