Versions Compared

Key

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

...

Do not cast away a const qualification to attempt to modify the resulting object. The const qualifier implies that the API designer does not intend for that object to be modified , despite the possibility it may be modifiable. Do not cast away a volatile qualification; the volatile qualifier implies that the API designer intends the object to be accessed in ways unknown to the compiler, and any access of the volatile object results in undefined behavior.

Noncompliant Code Example

...

In this noncompliant code example, a const-qualified method is called, which attempts to cache results by casting away the const-qualifier of this. Since Because s was declared const, the mutation of CachedCalc results in undefined behavior.

...

EXP35-EX1: An exception to this rule is allowed when it is necessary to cast away const when invoking a legacy API that does not accept a const argument, provided the function does not attempt to modify the referenced variable. It is always preferable to modify the API to be const-correct when possible, however. For example, the following code casts away the const qualification of INVFNAME in the call to the audit_log() function.

...

If the object is declared as being constant, it may reside in write-protected memory at runtime. Attempting to modify such an object may lead to abnormal program termination, or a denial-of-service attack. If an object is declared as being volatile, the compiler can make no assumptions regarding access of that object. Casting away the volatility of an object can result in reads or writes to the object being reordered, or elided entirely, resulting in abnormal program execution.

...

Related Vulnerabilities

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

...