Versions Compared

Key

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

The assert() method is a convenient mechanism for incorporating diagnostic tests in code. Expressions used with the standard assert method should not have side effects. Typically, the behavior of the assert method depends on the status of a runtime property. If defined, the assert method is defined to evaluate its expression argument and abort if the result of the expression is convertible to false. If undefined, assertis defined to be a no-op. Consequently, any side effects resulting from evaluation of the expression in the assertion are lost in non-debugging versions of the code.

Noncompliant Code

...

Example

Code Block

void process(int index) {

...

assert(index++ > 0); /* side effect */

...


  /* ... */

...


}

Compliant Solution

Avoid the possibility of side effects in assertions.

Code Block

void process(int index) {

...


  assert(index > 0); /* no side effect */

...


  ++index;

...


  /* ... */

...


}

Compliant Solution (Template)

Avoid the possibility of side effects in assertions.template <class Cont>
void process( Cont &c, size_t index ) {
size_t const size = c.size();
assert( index < size ); // no side effect
// ...

Risk Assessment

Side effects in assertions can lead to unexpected and erroneous behavior.

...

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

Other Languages

Wiki Markup
This rule appears in the C+\+ and C Secure Coding
Standard as 
 Standard as&nbsp;[EXP31-CPP. Avoid side effects in assertions|https://www.securecoding.cert.org/confluence/display/cplusplus/EXP31-CPP.+Avoid+side+effects+in+assertions] and \[EXP31-C. Avoid side effects in assertions

../display/seccode/EXP31-C.+Avoid+side+effects+in+assertions]

...