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

Compare with Current View Page History

« Previous Version 7 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 [[EXP05-A]] not to cast away a const-qualification as this makes it possible to modify a const-qualified value without warning.

Non-Compliant Code Example

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

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

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

The first assignment is unsafe because it would allow the following valid code 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 in both cases.

Compliant Solution

The compliant solution depends on the intention of the programmer. If the intention is that the value of c is modifiable, than 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.

Priority: P2 Level: L3

Integer truncation errors can lead to buffer overflows and the execution of arbitrary code by an attacker.

Component

Value

Severity

1 (low)

Likelihood

1 (unlikely)

Remediation cost

2 (medium)

References

  • ISO/IEC 9899-1999 Section 6.7.3 Type qualifiers, Section 6.5.16.1 Simple assignment
  • No labels