Versions Compared

Key

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

...

Programmers should exercise caution if the second operand contains side effects because it may not be apparent whether the side effects actually occur.

...

Code Block
enum { max = 15 };
int i = /* Initialize to user -supplied value */;

if ( (i >= 0) && ( (i++) <= max) ) {
  /* Code */
}

...

Noncompliant Code Example

In this noncompliant code example, the second operand of the logical OR operator invokes a function that results in side effects:

Code Block
bgColor#ffcccc
langc
char *p = /* Initialize,; may or may not be NULL */

if (p || (p = (char *) malloc(BUF_SIZE)) ) {
  /* Do stuff withPerform some computation based on p */
  free(p);
  p = NULL;
}
 else {
  /* Handle malloc() error */
  return;
}

...

Code Block
bgColor#ccccff
langc
char *p = /* Initialize; may or may not be NULL */
char *q = NULL;
if (p == NULL) {
  q = (char *) malloc(BUF_SIZE);
  p = q;
}
if (p == NULL) {
  /* Handle malloc() error */
  return;
}

/* Perform Dosome computation stuffbased withon p */
free(q);
q = NULL;

Risk Assessment

Failing to understand the short-circuit behavior of the logical OR or AND operator may cause unintended program behavior.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

EXP02-C

low

Low

unlikely

Unlikely

medium

Medium

P2

L3

Automated Detection

Tool

Version

Checker

Description

Astrée
Include Page
Astrée_V
Astrée_V
logop-side-effectFully checked
Axivion Bauhaus Suite

Include Page
Axivion Bauhaus Suite_V
Axivion Bauhaus Suite_V

CertC-EXP02Fully implemented
Compass/ROSE

 

 



Could detect possible violations of this recommendation by reporting expressions with side effects, including function calls, that appear on the right-hand side of an && or || operator

Helix QAC

Include Page
Helix QAC_V
Helix QAC_V

C3415
Klocwork
Include Page
Klocwork_V
Klocwork_V
MISRA.LOGIC.SIDEEFF
LDRA tool suite
Include Page
LDRA_V
LDRA_V

35 D
1 Q
133 S
406 S
408 S

Fully implemented

PRQA QA-C Include PagePRQA_VPRQA_V3415

Parasoft C/C++test
Include Page
Parasoft_V
Parasoft_V
CERT_C-EXP02-a

The right-hand operand of a logical && or || operator shall not contain side effects

PC-lint Plus

Include Page
PC-lint Plus_V
PC-lint Plus_V

9007

Fully supported

RuleChecker
Include Page
RuleChecker_V
RuleChecker_V
logop-side-effectFully checked
SonarQube C/C++ Plugin
Include Page
SonarQube C/C++ Plugin_V
SonarQube C/C++ Plugin_V
SideEffectInRightHandSideOfLogical
Fully implemented

Related Vulnerabilities

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

Related Guidelines

...


...

Image Modified Image Modified Image Modified