Versions Compared

Key

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

...

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/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 if a null-terminated byte string is assumed.

...

This noncompliant code example initializes an array of characters using a string literal that defines one character more character (counting the terminating '\0') than the array can hold:

...

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. */

Also, you should make clear in comments or documentation if a character array is, in fact, not a null-terminated byte string.

...

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

STR36-C

highHigh

probableProbable

lowLow

P18

L1

Automated Detection

Tool

Version

Checker

Description

Compass/ROSE

 

 

 

ECLAIR

Include Page
ECLAIR_V
ECLAIR_V

CC2.STR36

Fully implemented

PRQA QA-C
Include Page
PRQA_V
PRQA_V
1312Partially implemented

Splint

Include Page
Splint_V
Splint_V

 

 

...

[ECTC 1998]Section A.8, "Character Array Initialization"
[ISO/IEC 9899:2011]Subclause 6.7.9, "Initialization"
[Seacord 2013]Chapter 2, "Strings"

...