...
Programmers should exercise caution if the second operand contains side effects because it may not be apparent whether the side effects actually occur.
...
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 | ||||
---|---|---|---|---|
| ||||
char *p = /* Initialize; may or may not be NULL */ if (p || (p = (char *) malloc(BUF_SIZE)) ) { /* Perform some Docomputation stuffbased withon p */ free(p); p = NULL; } else { /* Handle malloc() error */ return; } |
...
Code Block | ||||
---|---|---|---|---|
| ||||
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 some Docomputation 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 | Unlikely | Medium | P2 | L3 |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Astrée |
| logop-side-effect | Fully checked | ||||||
Axivion Bauhaus Suite |
| CertC-EXP02 | Fully 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 | |||||||||
Helix QAC |
| C3415 | |||||||
Klocwork |
| MISRA.LOGIC.SIDEEFF | |||||||
LDRA tool suite |
| 35 D | Fully implemented |
Parasoft C/C++test |
| CERT_C-EXP02-a | The right-hand operand of a logical && or || operator shall not contain side effects | ||||||
PC-lint Plus |
| 9007 | Fully supported | ||||||
RuleChecker |
| logop-side-effect | Fully checked | ||||||
SonarQube C/C++ Plugin |
| SideEffectInRightHandSideOfLogical |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
SEI CERT C++ |
Coding Standard | VOID EXP02-CPP. Be aware of the short-circuit behavior of the logical AND and OR operators |
MITRE CWE | CWE-768, Incorrect short circuit evaluation |
...
...