From simon.urbanek at r-project.org  Thu Aug 29 21:35:33 2013
From: simon.urbanek at r-project.org (Simon Urbanek)
Date: Thu, 29 Aug 2013 15:35:33 -0400
Subject: [Rd] Why does an empty vector occupy 40 bytes?
In-Reply-To: <CABdHhvGoM-bHcH0Q-zcWGwRZsRQzb4gU3yNvL6kNb2PHdF2Z0w@mail.gmail.com>
References: <CABdHhvFchkfQagqO1xJbEn9MbePFLO6VR4kaNhUYgzyB6Jp8tg@mail.gmail.com>
	<521F6474.40307@stats.ox.ac.uk>
	<CABdHhvHZ2RYd_TGrehUSUt5xw6y-pgNbxQ8Tpu0jiAj145Z5KQ@mail.gmail.com>
	<7447F5AA-A29E-412B-8DEF-25D6F796FF16@r-project.org>
	<CABdHhvGayo-GatxtrMW6oCR9a3fBbw_1gJ2Y0hvv63QMT7dDFQ@mail.gmail.com>
	<B6D87831-7F8A-4474-B4A9-0021FC71B486@r-project.org>
	<CABdHhvGoM-bHcH0Q-zcWGwRZsRQzb4gU3yNvL6kNb2PHdF2Z0w@mail.gmail.com>
Message-ID: <0D4AE14D-4C68-4AD3-93C1-F01BCB66C82A@r-project.org>

On Aug 29, 2013, at 3:26 PM, Hadley Wickham wrote:

>>> Do pointers always have to be aligned?
>> 
>> Depends on the architecture, e.g., Sparc doesn't allow non-aligned pointers at all (results in a segfault), SV x86_64 ABI specifies pointers to be aligned at 8 bytes, but the x86_64 CPUs will allow misaligned pointers with a performance penalty (the same was true for x86 - i.e. misaligned pointers are tolerated with a penalty).
> 
> Ok, so you might not have to align pointers a particular architecture,
> but if you're writing code that you want to work across multiple
> architectures you must.
> 

Yes. In many cases the compiler does that for you (e.g. inside structs), but if you are constructing binary objects that will be loaded into memory directly and then accessed then, yes, you have to take that into account. Note that the alignment requirements are not just for pointers but for all types, e.g., Sparc also segfaults if you don't align doubles on 8-byte boundary.

It is also a good idea to have alignment in mind when designing structs, e.g.:

struct a {
    char flag;
    char *name;
    char active;
    char *description;
    int  len;
};

takes 40 bytes on 64-bit machine, while just re-ordering the members to

struct b {
    char *name;
    char *description;
    char flag;
    char active;
    int  len;
};

takes 24 bytes.

Cheers,
Simon


> Hadley
> 
> -- 
> Chief Scientist, RStudio
> http://had.co.nz/
> 
> 



[Rd] Why does an empty vector occupy 40 bytes?
Simon Urbanek