Re: Alignment - Structures and Other Things

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

 



On Apr 13, 2011, at 3:26 PM, Andrew Bell wrote:

> 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

Hmm, very interesting. Is it possible to determine what the memory alignment requirements are on a given implementation? Or at least with GCC in specific? It can be either a compile time or a runtime solution, either is good for my purposes.

Or do you really have to go and manually look at the documentation for every system+arch you're releasing on, and manually keep track of alignment requirements?

I wrote a little test case which allocates a few dozen memory blocks with malloc() and then examines them to guess what the system's alignment seems to be, but obviously I don't want to use that as a final solution.

-Patrick




[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