Re: are statically allocated structs always aligned to a machine word on x86/x86_64?

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

 



On 21 August 2015 at 20:31, john smith <wempwer@xxxxxxxxx> wrote:
> On Fri, Aug 21, 2015 at 8:49 PM, Jonathan Wakely <jwakely.gcc@xxxxxxxxx> wrote:
>> On 21 August 2015 at 19:39, john smith wrote:
>>> I didn't find any information about alignment requirements for
>>> statically allocated objects in GCC and x86-64 manual (or I have
>>> missed because the manual is huge). I noted that sometimes variables
>>> such as int are not aligned on word boundary in x86 and x86_64 but I
>>> have never seen a struct that wouldn't be allocated at address that
>>> isn't a multiple or 4/8.
>>
>> Three of these structs are not word-aligned:
>>
>> #include <stdio.h>
>> struct A { char c; };
>> struct A a[4];
>>
>> int main()
>> {
>>   for (int i=0; i<4; ++i)
>>     printf("%p\n", a+i);
>> }
>
>
> Hmm... Ok, but it's only when they only char whose alignment is 1. If
> the struct declaration would be changed to this all of them would be
> aligned at a word boundary:
>
> struct A { char c; long l;};
>
> So my question would rather be: if struct contains a type whose
> alignment is bigger than 1 is it always word-aligned?.

No. It could have an alignment of 2, and not be word-aligned if a word
is 4 bytes.

#include <stdio.h>
struct A { short s; };
struct A a[2];

int main()
{
  printf("%zu\n", _Alignof(struct A));
  for (int i=0; i<2; ++i)
    printf("%p\n", a+i);
}


If a type has an alignment that is smaller than the size of a word,
then it doesn't have to be word aligned.

If it has an alignment that is equal to the size of a word then it
will be word aligned, by definition.

If it has a larger alignment then it will also be word-aligned,
because alignments must be a power of 2.



[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