You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 60 Next »

Two consecutive question marks signify the start of a trigraph sequence. According to the C99 Standard [ISO/IEC 9899:1999]

All occurrences in a source file of the following sequences of three characters (that is, trigraph sequences) are replaced with the corresponding single character.

??=

#

 

??)

]

 

??!

|

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="5c0a9d96-cae1-41db-9174-6c2e2f3f1adb"><ac:plain-text-body><![CDATA[

??(

[

 

??'

^

 

??>

}

]]></ac:plain-text-body></ac:structured-macro>

??/

\

 

??<

{

 

??-

~

Noncompliant Code Example

In this noncompliant code example, a++ is not executed because the trigraph sequence ??/ is replaced by \, logically putting a++ on the same line as the comment.

// what is the value of a now??/
a++;

Compliant Solution

The following compliant solution eliminates the accidental introduction of the trigraph by separating the question marks.

// what is the value of a now? ?/
a++;

Noncompliant Code Example

This noncompliant code example includes the trigraph sequence ??!, which is replaced by the character |.

size_t i = /* some initial value */;
if (i > 9000) {
   if (puts("Over 9000!??!") == EOF) {
     /* Handle Error */
   }
}

This example prints Over 9000!| if a C99-compliant compiler is used.

Compliant Solution

This compliant solution uses string concatenation to concatenate the two question marks; otherwise, they are interpreted as beginning a trigraph sequence.

size_t i = /* some initial value */;
/* assignment of i */
if (i > 9000) {
   if (puts("Over 9000!?""?!") == EOF) {
     /* Handle Error */
   }
}

The above code prints Over 9000!??!, as intended.

Risk Assessment

Inadvertent trigraphs can result in unexpected behavior. Some compilers provide options to warn when trigraphs are encountered or to disable trigraph expansion. Use the warning options and ensure your code compiles cleanly. (See recommendation MSC00-C. Compile cleanly at high warning levels.)

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

PRE07-C

low

unlikely

medium

P2

L3

Automated Detection

Tool

Version

Checker

Description

9.7.1

81 S

Fully Implemented

GCC

4.3.5

 

can detect violation of this recommendation when the -Wtrigraphs flag is used

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

CERT C++ Secure Coding Standard: PRE07-CPP. Avoid using repeated question marks

ISO/IEC 9899:1999 Section 5.2.1.1, "Trigraph sequences"

MISRA 2004 Rule 4.2

Bibliography


PRE06-C. Enclose header files in an inclusion guard      01. Preprocessor (PRE)      

  • No labels