Does unaligned memory access always cause bus errors?

user172818 picture user172818 · Sep 30, 2009 · Viewed 7.5k times · Source

According to the Wikipedia page Segmentation fault, a bus error can be caused by unaligned memory access. The article gives an example about how to trigger a bus error. In the example, we have to enable alignment checking to see the bus error. What if we disable such alignment checking?

The program seems to work properly. I have a program access unaligned memory frequently, and it is used by quite a few people, but no one reports bus errors or other weird results to me. If we disable alignment checking, what is the side effect of unaligned memory?

Platforms: I am working on x86/x86-64. I also tried my program by compiling it with "gcc -arch ppc" on a Mac and it works properly.

Answer

Pavel Minaev picture Pavel Minaev · Sep 30, 2009
  1. It may be significantly slower to access unaligned memory (as in, several times slower).

  2. Not all platforms even support unaligned access - x86 and x64 do, but ia64 (Itanium) does not, for example.

  3. A compiler can emulate unaligned access (VC++ does that for pointers declared as __unaligned on ia64, for example) - by inserting additional checks to detect the unaligned case, and loading/storing parts of the object that straddle the alignment boundary separately. That is even slower than unaligned access on platforms which natively support it, however.