Re: Error msg - unaligned trap
On Wed, Nov 07, 2001 at 04:14:41PM -0600, Gunnar Wolf wrote:
>
> Why does this happen? Most times, I don't really know. It usually is
> because GCC may be a great 32-bit compiler, but is not so great when
> producing 64-bit code (I think this has been getting better with the
> latest releases).
An unaligned access is usually not a compiler problem, it's a programmer
error. It crops up when a pointer is improperly cast to a type with
stricter alignment requirements, then dereferenced. For example:
void foo(char *p)
{
long l = *(long*) p; /* dangerous! p may not be word-aligned */
}
Alignment traps happen on 32-bit architectures like ARM as well as on
64-bit ones. They are more common on 64-bit architectures partly because
ints and pointers are different lengths, and partly because 64-bit archs
are rare (so programmers get away with hacks like using "!(3 & foo)"
to test word-alignment; see below).
x86 doesn't have rigid alignment requirements, but modern x86
implementations are a lot faster when memory accesses are aligned,
so fixing alignment bugs is a Good Thing.
There isn't a lot of code with a legitimate reason to care about
alignment, but when there _is_ a need (e.g. optimizing memory copies or
other twiddling) you need to test alignment manually, and often write
arch-specific code:
#ifdef __alpha__
if (7 & (unsigned long) p) {
/* slow version for unaligned data */
} else {
/* fast full-word version */
}
#endif
You'd probably want more abstraction than that if you were really writing
production multi-platform code, something like an IS_WORD_ALIGNED() macro.
miket
Reply to: