C Language Aliasing and effective type Changing bytes


Example

Once an object has an effective type, you should not attempt to modify it through a pointer of another type, unless that other type is a character type, char, signed char or unsigned char.

#include <inttypes.h>
#include <stdio.h>

int main(void) {
  uint32_t a = 57;
  // conversion from incompatible types needs a cast !
  unsigned char* ap = (unsigned char*)&a;
  for (size_t i = 0; i < sizeof a; ++i) {
    /* set each byte of a to 42 */
    ap[i] = 42;
  }
  printf("a now has value %" PRIu32 "\n", a);
}

This is a valid program that prints

a now has value 707406378

This works because:

  • The access is made to the individual bytes seen with type unsigned char so each modification is well defined.
  • The two views to the object, through a and through *ap, alias, but since ap is a pointer to a character type, the strict aliasing rule does not apply. Thus the compiler has to assume that the value of a may have been changed in the for loop. The modified value of a must be constructed from the bytes that have been changed.
  • The type of a, uint32_t has no padding bits. All its bits of the representation count for the value, here 707406378, and there can be no trap representation.