title: mmap memory alignment in ARM
body: <p>I'm working on a project that's being ported to ARM7 (was originally on x86). It runs on QNX. We've had a few memory alignment issues (SIGBUS error crashes) due to reading/writing with misaligned pointers. I've been fixing most alignment issues simply by replacing the pointer casting and assignment with a memcpy, but this issue I can't solve like that.</p>
  
  <p>There's a memory pool shared between processes that's initialized like this:</p>
  
  <pre><code>int m_nSharedMemory = shm_open(EVENT_LIST_NAME, O_RDWR | O_CREAT, 0777);
  ftruncate(m_nSharedMemory, nSize)
  unsigned char* m_pMemory = (unsigned char*) mmap(0, nSize, PROT_READ | PROT_WRITE, MAP_SHARED, m_nSharedMemory, 0); 
  </code></pre>
  
  <p>The memory is supposed to be used like this: there's a <code>Header</code> at the beginning of the address space and there's an <code>Event</code> array afterwards. Thus, <code>nSize = sizeof(Header) + MAX_EVENTS * sizeof(Event)</code>.</p>
  
  <pre><code>m_pHeader = (Header*)m_pMemory;
  m_pEvents = (Event*)(m_pMemory + sizeof(Header));
  </code></pre>
  
  <p>Both <code>Header</code> and <code>Event</code> are structs with primitive types. As far as I know, this memory is not aligned, so doing <code>m_pEvents[0].m_SomeField == 3</code> or <code>m_pHeader-&gt;m_SomeField = 1</code> could potentially trigger a SIGBUS error. This kind of instructions are everywhere, so replacing each one with memcpy would be a real pain, I'm hoping I can get away with something else.</p>
  
  <p>I've found <code>posix_memalign</code> which I believe could replace either <code>shm_open</code> or <code>mmap</code>, not sure which yet, but this doesn't seem to solve the issue either. For one, I still get the warning. Even ignoring the warning, I could make sure memory is aligned to <code>sizeof(Header)</code>, but <code>m_pEvents</code> wouldn't be aligned.</p>
  
  <p>Is there any way to prevent a SIGBUS error without making major modifications to this scheme? Right now the compiler is complaining because <code>"cast from 'unsigned char*' to 'Header*' increases required alignment of target type"</code> (there's a similar warning for <code>Event</code>), but the program is not crashing, which I really can't explain.</p>
  
  <p>So, two questions: 1) Why doesn't it crash? 2) How do I make sure it never will, ideally by ensuring that memory is aligned and supressing the warning</p>