views:

426

answers:

2

According to this wiki page, bus error can be caused by unaligned memory access. The wiki page 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 error or other weird results to me. The question is if we disable alignment checking, what is the side effect of unaligned memory?

+6  A: 
  1. It is 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.

Pavel Minaev
Thanks. Few users of my program are working on ia64. Maybe that is why I have not received bug report.
You miht also add #4 that an OS can emulate unaligned access onbehal of an application by catching the processor exception and fixing it up (kind of like what happens for a page fault). This is slower than the compiler perofrming unaligned fix ups in the generated code. Windows can support this in ia64.
Michael Burr
+2  A: 

Very much depends on the chip architecture x86 and Power are very forgiving, Sparc, Itanium and VAX through different exceptions.

James Anderson
Many thanks for the answer.
It does indeed depend on the processor. I recently worked on a DSP that will happily proceed by using the closest aligned memory address when asked to operate on an unaligned one. Debug *that*, you perverted unaligned memory accessing individual.
Dan Moulding
Indeed, why bother even looking at those last few bits at all - Real Men know what they're doing, anyway :) On the other hand, it would be a convenient architecture to use tagged pointers on, if you use the ignored bits for the tag...
Pavel Minaev
Steve Jessop