Versions Compared

Key

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

An object that has volatile-qualified type may be modified in ways unknown to the implementation or have other unknown side effects. 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:

...

Non-Compliant Code Example

This non-compliant code example allows a constant value to be modified.In this example, a volatile object is accessed through

Code Block
int main(void) {
  static volatile charint **cppipp;
char  static int *cpip;
  static volatile char c = 'A';

cpp int i = 0;;

  printf("i = %d.\n", i);

  ipp = &cpip; // constraint violation
  *cppipp = &ci; // valid
  if (*cpip != 'B'; 0) { // valid
	// i had been changed
  }
}

The first assignment is unsafe because it would allow the following valid code to attempt to reference the
value of the volatile object c i through a non-volatile qualified reference.

Implementation Specific Details

If cpp, cp, and c are declared as automatic (stack) variables, this 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 In this 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.the int * ip is declared as volatile.

Code Block

int main(void) {
  static volatile int **ipp;
  static volatile int *ip;
  static volatile int i = 0;;

  printf("i = %d.\n", i);

  ipp = &ip; // constraint violation
  *ipp = &i; // valid
  if (*ip != 0) { // valid
    /* i has changed */
  }

Priority: P2 Level: L3

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

...