Versions Compared

Key

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

Modifying a variable through a pointer of an incompatible type can lead to unpredictable results. This is often caused by a violation of aliasing rules. C11, Section 6.5, paragraph para. 7 [ISO/IEC 9899:2011], specifies those circumstances in which an object may or may not be aliased.

...

The programmer in this noncompliant code example is attempting to read from a different union member than the one most recently written to; this is known as " type-punning."

Code Block
bgColor#FFCCCC
langc
union a_union {
  int i;
  double d;
};

int f() {
  a_union t;
  int *ip;
  t.d = 3.0;
  ip = &t.i;
  return *ip;
}

However, instead of reading directly from union member, it assigns a pointer ip to reference the integer value and returns the value referenced by the pointer. Unfortunately, this is a violation of the strict aliasing rules, and in this case the compiler may determine that ip refers to some other value than the value stored by t.i and return a value other than the expected value.

...

Optimizing for performance can lead to aliasing errors which can be quite difficult to detect. Furthermore, as in the case abovepreceding example, unexpected results can lead to buffer overflow attacks and/or bypassing security checks and/or unexpected execution.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

EXP39-C

medium

unlikely

high

P2

L3

Related Guidelines

ISO/IEC 9899:2011 Section  Section 6.5, "Expressions"

ISO/IEC TR 17961 (Draft) Accessing an object through a pointer to an incompatible type [ptrcomp]

...