title: Casting array pointer to another type gives different output for different compiler optimizations
body: <p>I was trying the <code>reinterpret_cast</code> in C++, but then I noticed an inconsistency with it. It gave different outputs for different optimization levels. Then I tried the C-version of it and it gave the wrong output again.</p>
  <p>This is the C code:</p>
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  int main(int argc, char const *argv[]) {
      unsigned long long* arr = (unsigned long long*)malloc(16);
      arr[0] = 0x300000061;
      arr[1] = 9;
      int* casted = (int*)(arr);
      for (int i = 0; i &lt; 3; ++i)
          printf(&quot;%d\n&quot;, casted[i]);
      return 0;
  }
  </code></pre>
  <p>Notice the <code>int* casted = (int*)(arr);</code> where it casts the pointer. When instead casting to char* and increasing 3 to 12 in the for-loop it gives the output I expect.</p>
  <p>Output with O1-O3 flag:</p>
  <pre><code>0
  0
  0
  </code></pre>
  <p>Output without any O flag:</p>
  <pre><code>97
  3
  9
  </code></pre>
  <p>Output with char (with or without optimization):</p>
  <pre><code>97
  0
  0
  0
  3
  0
  0
  0
  9
  0
  0
  0
  </code></pre>
  <p>The second output is what I would expect. Is this kind of pointer casting undefined behaviour or is it a compiler bug?</p>
  <p>I use the WSL gcc compiler.</p>
  <p>Edit:
  Thanks for the quick response. Is there a way to write an asm function to get the desired output? I know I could use memcpy() instead but I need to use this in a specific problem I can't explain easily, so I'd rather not.</p>