It is possible to reference a volatile object by using a non-volatile value but the resulting behavior is undefined. According to C99 Section 6.7.3 Type qualifiers Paragraph 5:
If an attempt is made to refer to an object defined with a volatile-qualified type through use of an lvalue with non-volatile-qualified type, the behavior is undefined.
This also applies to objects that behave as if they were defined with qualified types such as an object at a memory-mapped input/output address.
Non-Compliant Code Example
This non-compliant code example allows a constant value to be modified.
volatile char **cpp; char *cp; volatile 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 reference the
value of the volatile 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