technovelty

weblog of Ian Wienand

RSS  |  technovelty home  |  page of ian  |  ianw@ieee.org

on structure alignment

C99 states (6.7.2.1 - 12)

Each non-bit-field member of a structure or union object is aligned in an implementation defined manner appropriate to its type.

For example, gcc 4 has changed the way structures line up on the stack for IA64.

#include 

struct disk_stat {
        int fd;
        unsigned count;
};

int main(void)
{
        int blah;
        struct disk_stat test;

        printf("%p\n", &test);
}
ianw@lime:/tmp$ vi test.c
ianw@lime:/tmp$ gcc-4.0 -o test test.c
ianw@lime:/tmp$ ./test
0x60000fffff8eb480
0x60000fffff8eb484
ianw@lime:/tmp$ gcc-3.4 -o test test.c
ianw@lime:/tmp$ ./test
0x60000fffffafb470
0x60000fffffafb480

This is allowable because the two members of the structure (ints) only require 4 byte alignment. Although it may make for worse code; I guess the lesson is think about how your structure might be layed out and if required give it explicit alignment.

posted at: Wed, 20 Jul 2005 16:07 | in /code/c | permalink | add comment (0 others)

Add a comment
*Name
*Email (not shown)
Website
*Comment:
*Word above?
* denotes required field

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License.