...
Although the behavior is well-defined, it is not immediately obvious whether i gets incremented or not.
...
Noncompliant Code Example
In this code example, the second operand of the logical OR operator invokes a function that results in side effects.
...
Because malloc()
is only called if p
is NULL when entering the if
clause, free()
might be called with a pointer to local data not allocated by malloc()
(see MEM34-C. Only free memory allocated dynamically). This is partially due to the uncertainty of whether malloc()
is actually called or not.
Compliant Solution
In this compliant solution, a second pointer, q
, is used to indicate whether malloc()
is called; if not, q
remains set to NULL. Passing NULL to free()
is guaranteed to safely do nothing.
Code Block | ||
---|---|---|
| ||
char *p; char *q = NULL; if (p == NULL) { q = (char *) malloc(BUF_SIZE); p = q; } if (p == NULL) { /* handle malloc() error */ return; } /* do stuff with 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-A C | low | unlikely | medium | P2 | L3 |
Automated Detection
The LDRA tool suite V 7.6.0 is able to can detect violations of this recommendation.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.5.13, "Logical AND operator," and Section 6.5.14, "Logical OR operator" |
...
EXP01-C. Do not take the size of a pointer to determine the size of the pointed-to type 03. Expressions (EXP) EXP03-A. Do not assume the size of a structure is the sum of the sizes of its members