This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

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


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?. I am well aware
of sizeof(). I just want to educate myself. x86_64 ABI says that
objects don't have to be aligned and it also says that "structs and
unions assume the alignment of their most strictly aligned
component". After a bit of thinking I think I got it: on x86_64 even
if c was allocated on 6th, 7th or 8th byte of the word l that follows
must be allocated at the beginning of the next word. Whole size of
struct would be 11, 10, and 9 bytes respectively. It would still be
necessary to allocate 5, 6, or 7 extra bytes to make size of this
struct be a multiple of 16. And in such manner the whole struct would
be spanned across 3 words. As it's more efficient for a CPU to access
data that is word alignment, it always makes sense to allocate such
structs that contain non-char elements on the first byte of the
world. Is that thinking correct?

I still have to wrap my head around how is all of these related to the
virtual memory concept and paging.

-- 
<wempwer@gmail.com>


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]