Versions Compared

Key

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

...

It is common for an array variable to be declared with both initialized by a string literal , and a size index which specifies and declared with an explicit dimension which matches the number of characters in the string literal. This is 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. As a result, the size index for a character array must never be explicit.

A better approach is to not specify the dimension of a string initialized with a string literal, as the compiler will automatically allocate sufficient space for the entire string literal, including the terminating null character. This rule is a specific exception to ARR02-A. Explicitly specify array dimensions, even if implicitly defined by an initializer.

Initializing a character array using a string literal to fit exactly without a null byte is not allowed in C++.This rule is related to ARR02-A. Explicitly specify array dimensions, even if implicitly defined by an initializer.

Non-Compliant Code Example

The following 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.

...

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).

Compliant Solution

This compliant solution does not specify the dimension of a character array in the array declaration. By omitting the sizeIf the array dimension is omitted, the array will automatically be of appropriate length compiler will allocate sufficient storage to store the full entire string literal, including the terminating null character.

Code Block
bgColor#ccccff
char s[] = "abc";

...

Wiki Markup
\[[ECTC 98|AA. C References#ECTC 98]\] A.8, "Character array initialization"
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.7.8, "Initialization"
\[[Seacord 05a|AA. C References#Seacord 05a]\] Chapter 2, "Strings"

...