"BartC" <> writes:
[...]
> Alternatively, don't compilers have a 'pack' directive for exactly this
> purpose? Again this would be conditional. Ideally a way of controlling
> alignment on a field-by-field basis is needed.
Yes, some compilers have a pack directive, but it doesn't always work.
For example, on SPARC, attempting to access a misaligned object causes
the program to crash. Here's a program that uses gcc's
__attribute__((packed)) extension:
#include <stdio.h>
int main(void) {
struct unpacked {
char c;
double d;
};
struct packed {
char c;
double d;
} __attribute__((packed));
struct unpacked u[2] = { { 'u', 1.2 }, { 'U', 3.4 } };
struct packed p[2] = { { 'p', 5.6 }, { 'P', 7.8 } };
double *up0 = &u[0].d;
double *up1 = &u[1].d;
double *pp0 = &p[0].d;
double *pp1 = &p[1].d;
printf("*up0 = %g\n", *up0);
printf("*up1 = %g\n", *up1);
printf("*pp0 = %g\n", *pp0);
printf("*pp1 = %g\n", *pp1);
return 0;
}
And here's the output I got:
*up0 = 1.2
*up1 = 3.4
Bus error
If you refer to the misaligned member directly, so the compiler
knows that it's misaligned, it can access it correctly. If you've
saved a pointer to the misaligned member, there's no way for the
compiler to know that it's misaligned.
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
Will write code for food.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"