title: How can unions be used to bypass strict aliasing violations?
body: <p>According to <a href="https://stackoverflow.com/a/61179390">this answer</a> the following code invokes undefined behavior:</p>
  <pre><code>uint16_t *buf = malloc(16); // 8*sizeof(uint16_t)
  buf[1] = *buf = some_value;
  ((uint32_t *)buf)[1] = *(uint32_t *)buf;
  ((uint64_t *)buf)[1] = *(uint64_t *)buf;
  </code></pre>
  <p>We may write any type to <code>malloc()</code> memory but we may not read a previously written value as an incompatible type by casting pointers (with the exeption of <code>char</code>).</p>
  <p>Could I use this union:</p>
  <pre><code>union Data {
      uint16_t u16[8];
      uint32_t u32[4];
      uint64_t u64[2];
  };
  </code></pre>
  <p>As such:</p>
  <pre><code>union Data *buf = malloc(16);
  buf-&gt;u16[1] = buf-&gt;u16[0] = some_value;
  buf-&gt;u32[1] = buf-&gt;u32[0];
  buf-&gt;u64[1] = buf-&gt;u64[0];
  </code></pre>
  <p>In order to avoid undefined behavior via strict aliasing violations? Also, could I cast <code>buf</code> to any of <code>uint16_t *</code>, <code>uint32_t *</code>, <code>uint64_t *</code>, and then dereference it without invoking undefined behavior, since these types are all valid members of <code>union Data</code>? (i.e. is the following valid):</p>
  <pre><code>uint16_t first16bits = *(uint16_t *)buf;
  uint32_t first32bits = *(uint32_t *)buf;
  uint64_t first64bits = *(uint64_t *)buf;
  </code></pre>
  <p>If not (i.e. the above code making use of <code>union Data</code> is still invalid), when can and cannot unions be used (in pointer casts or otherwise) to produce valid code that does not violate strict aliasing rules?</p>