Skip to content
Prev 46550 / 63424 Next

Why does an empty vector occupy 40 bytes?

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

            
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