Alignment - Structures and Other Things
Andrew Bell
andrew.bell.ia@gmail.com
Wed Apr 13 19:26:00 GMT 2011
On Wed, Apr 13, 2011 at 2:09 PM, Patrick Rutkowski <rutski89@gmail.com> wrote:
> I'm confused about if and how memory alignment relates to struct types. Say you have a struct like so:
>
> struct foo
> {
> int a;
> char b;
> float c;
> };
>
> Now, in the typical use case instances of type foo will be allocated either on the stack or on the heap via malloc(), so in either case it's the implementation which decides if the struct's base address is going to be specially aligned in some way. But is this even really important for structs? What if I were to do something like the following:
>
> struct foo s;
> s.a = 7;
> s.b = 'a';
> s.c = 1.1f;
>
> char* bytes = malloc(1 + sizeof(struct foo));
> bytes++;
> *(struct foo*)bytes = s;
>
> Would the system be unhappy in any way because the struct is being stored in a region shifted by one by over from where malloc() might "want" it to be?
malloc() will return memory on a boundary suitable for any type. If
some types must be, say, 8-byte aligned, malloc will return memory
that is 8-byte aligned. This of course satisfies types that are
4-byte, 2-byte and non-aligned.
Your example code will end up breaking on some systems.
This has nothing to do with specifically with GCC.
--
Andrew Bell
andrew.bell.ia@gmail.com
More information about the Gcc-help
mailing list