Re: Alignment - Structures and Other Things

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Wed, Apr 13, 2011 at 2:09 PM, Patrick Rutkowski <rutski89@xxxxxxxxx> 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@xxxxxxxxx



[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux