typestar

Undefined behavior: strict aliasing in C

Reading an object through an unrelated pointer type breaks the aliasing rule.

#include <string.h>

/* Undefined: an int object read as a float. */
float punned(int bits) {
    return *(float *) &bits;
}

/* Defined: copy the bytes into a real float. */
float reinterpreted(int bits) {
    float value;
    memcpy(&value, &bits, sizeof value);
    return value;
}

unsigned char first_byte(const void *object) {
    return *(const unsigned char *) object;
}

How it works

  1. Only a char pointer may alias any object.
  2. Casting an int pointer to a float pointer is undefined.
  3. memcpy between the two is the defined way to reinterpret.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
358
Tokens
69
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 39 seconds.

Type this snippet

Step 2 of 3 in Undefined behavior, step 9 of 13 in Unions, bitfields & undefined behavior.

← Previous Next →