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

Compare with Current View Page History

Version 1 Next »

Use parenthesis around any macro definition that contains operators.

Non-Compliant Coding Example

In this non-compliant coding example, EOF is defined as -1. This macro definition consists of a unary negation operator '-' followed by an integer literal '1'.

#define EOF -1
/* ... */
if (c EOF) {
   /* ... */
}

In this example, the programmer has mistakenly omitted the comparison operator (see [[MSC02-A. Avoid errors of omission]]) from the conditional statement which should be c != EOF. After macro expansion, the conditional expression is incorrectly evaluated as a binary operation: c-1. This is syntactically correct, even though it is certainly not what the programmer intended.

Parenthesizing the -1 in the declaration of EOF ensures that the macro expansion is evaluated correctly.

#define EOF (-1)

Once this modification is made, the non-compliant code example no longer compiles as the macro expansion results in the conditional expression c (-1), which is no longer syntactically valid.

Compliant Solution

The following compliant solution uses parenthesis around the macro definition and adds the (previously omitted) comparison operator.

#define EOF (-1)
/* ... */
if (c != EOF) {
   /* ... */
}

Risk Assessment

Failure to use parenthesis around macro definitions that contain operators can result in unintended program behavior.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

PRE05-A

1 (low)

1 (unlikely)

2 (medium)

P2

L3

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

References

[[Plum 85]] Rule 1-1
[[ISO/IEC 9899-1999]] Section 6.10, "Preprocessing directives," and Section 5.1.1, "Translation environment"

  • No labels