This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: are statically allocated structs always aligned to a machine word on x86/x86_64?
- From: Jonathan Wakely <jwakely dot gcc at gmail dot com>
- To: john smith <wempwer at gmail dot com>
- Cc: gcc-help <gcc-help at gcc dot gnu dot org>
- Date: Sun, 23 Aug 2015 00:15:56 +0100
- Subject: Re: are statically allocated structs always aligned to a machine word on x86/x86_64?
- Authentication-results: sourceware.org; auth=none
- References: <CAKmQUfZT04z8pd9bvqazEPkV1iqRrUxw82nxd3RbOerVbyxqhA at mail dot gmail dot com> <CAH6eHdQdAt1sqtnZe7CiJtWKb_SeggnXieiiR7Wf4D8Uf1sLyg at mail dot gmail dot com> <CAKmQUfbuZ-tbggq8iCxYd4G_VSnVgbS-jBzPc6AYxQhRtN65GQ at mail dot gmail dot com>
On 21 August 2015 at 20:31, john smith <wempwer@gmail.com> wrote:
> On Fri, Aug 21, 2015 at 8:49 PM, Jonathan Wakely <jwakely.gcc@gmail.com> 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.