title: Correctness of misaligned access in C++
body: <p>From what I have read, misaligned access means mostly two things:</p>
  
  <ol>
  <li>you <em>may</em> get a performance loss</li>
  <li>you <em>will</em> lose atomicity of loads and stores that aligned access has</li>
  </ol>
  
  <p>Supposing that performance is not an issue and what I want from software is correctness, how bad is misaligned access? My understanding is that the x86 CPU will handle such accesses correctly but may have to do additional work to fetch the data.</p>
  
  <p>What lead me to asking this question was compiling my code with <code>-fsanitize=undefined</code>. I got <strong>many</strong> errors about misaligned stores/loads. I am not sure if this is an issue because:</p>
  
  <ol>
  <li>the stores are performed only during data preparation which is a single-threaded process, so I am not concerned about loss of atomicity</li>
  <li>the loads are performed in a multithreaded process where many threads (four or more) access the data, but the data is not modified by any of them (held in a <code>const uint8_t*</code> variable)</li>
  </ol>
  
  <p>The reason accesses are not aligned is that the <code>const uint8_t*</code> array contains bytes from many different types (<code>uint8_t</code>, <code>uint16_t</code>, <code>uint32_t</code>, <code>uint64_t</code>, and <code>int64_t</code>).</p>
  
  <p>I am sure that no load goes outside the bounds of the allocated <code>uint8_t</code> array (e.g. the program never loads <code>uint64_t</code> from an address that points to last one, two, or three bytes of the allocated memory block), and am sure that my accesses are all <em>correct</em> - only misaligned.</p>
  
  <p>Another thing I read is that such loads may be breaking the strict aliasing rules, but the code compiles without a single warning with <code>-Wstrict-aliasing -Werror</code> (which I have long ago enabled).</p>
  
  <p>Should I pad the data in the <code>uint8_t</code> array to ensure accesses are aligned, or may I safely ignore the warnings?</p>