You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 24 Next »

It is possible to assign the value of a constant object by using a non-constant value, but the resulting behavior is undefined. According to C99 Section 6.7.3, "Type qualifiers," Paragraph 5:

If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.

There are existing (non-compliant) compiler implementations that allow const-qualified values to be modified without generating a warning message.

It is also a recommended practice not to cast away a const qualification ([[EXP05-A. Do not cast away a const qualification]]), as this makes it easier to modify a const-qualified value without warning.

Non-Compliant Code Example

This non-compliant code example allows a constant value to be modified.

char const **cpp;
char *cp;
char const c = 'A';

cpp = &cp; /* constraint violation */
*cpp = &c; /* valid */
*cp = 'B'; /* valid */

The first assignment is unsafe because it would allow the valid code that follows to attempt to change the value of the const object c.

Implementation Specific Details

If cpp, cp, and c are declared as automatic (stack) variables, this example compiles without warning on Microsoft Visual C++ .NET (2003) and on MS Visual Studio 2005. In both cases, the resulting program changes the value of c. Version 3.2.2 of the gcc compiler generates a warning but compiles. The resulting program changes the value of c.

If cpp, cp, and c are declared with static storage duration, this program terminates abnormally for both MS Visual Studio and gcc Version 3.2.2.

Compliant Solution

The compliant solution depends on the intention of the programmer. If the intention is that the value of c is modifiable, then it should not be declared as a constant. If the intention is that the value of c is not meant to change, then do not write non-compliant code that attempts to modify it.

Risk Assessment

Modifying constant objects through non-constant references results in undefined behavior.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXP31-C

1 (low)

1 (unlikely)

2 (medium)

P2

L3

Related Vulnerabilities

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

References

[[ISO/IEC 9899-1999]] Section 6.7.3, "Type qualifiers," and Section 6.5.16.1, "Simple assignment"

Footnotes

  • No labels