Hello All,
I really see where programmers strive to achievement alignment manually. For example,
struct {
char yo;
int slen;
char state;
}
I would see something of this nature,
struct {
int slen;
char yo;
char state;
}
On a system where `int' requires four-byte alignment, the first
struct is likely to take twelve bytes:
char yo; // one byte
// three-byte gap
int slen; // four bytes
char state; // one byte
// three-byte gap
.... while the second would probably need only eight:
int slen; // four bytes
char yo; // one byte
char state; // one byte
// two-byte gap
If the program creates many instances of this struct, using the
second instead of the first could cut memory use by one-third.
(Alternatively: Using the first instead of the second could bloat
memory by fifty percent.) Since modern CPU's are much faster than
modern memories, getting the same amount of "payload" into fewer
bytes might make a significant difference in speed, too.
On 32 bit machine, at times I see even dummies here and there to make sure that the whole thing is properly aligned.
That seems odd. The compiler will insert whatever padding is
needed, so why would the programmer need to get involved? Maybe it
would make some sense if the code used a non-standard extension like
`#pragma packed" or `__attribute__ ((aligned(N)))' to say that the
programmer, rather than the compiler, is assuming responsibility for
alignment -- but if the programmer then has to turn around and create
dummies, what's the point?
My guess is that the dummies aren't there for the purpose of
aligning things, but in order to match some externally-defined
format: An IP packet header or an on-disk inode or some such. It
is tempting to use structs for such purposes -- tempting, but
hazardous, since different compilers may lay out "the same" struct
differently.
I would need pointers on where to read more of this issue, and I also would like to hear from you on this.
Question 2.12 on the comp.lang.c FAQ page <
http://www.c-faq.com/>
is a good, if brief introduction. There are some useful links at the
bottom of the question page, too.