2
votes

As per my understanding, pointers on a 64 bit linux system are 8 bytes in size, and alignment requirement for these should be 8 byte aligned. If that's the case then why does new operator returns 16 byte (could be 32, but what matter is that this number is higher than 8) aligned pointer? Simple calls such as

struct alignas(8) SimpleChar     
{
    char c;
}

SimpleChar * c = new SimpleChar;
SimpleChar * c1 = new SimpleChar;

will allocate 32 bytes given each pointer is 16 bytes aligned. If instead I use placement new

 SimpleChar * c = new (slab) SimpleChar;
 SimpleChar * c1 = new (slab + 8) SimpleChar;

This will result into using 16 bytes for the two pointer types. My questions are as follows -

  1. Is 16 byte alignment of pointer return by operator new really necessary?
  2. Are there any side effects of using placement new and align every struct and pointer by 8 bytes? (One side effect I could think of is that this approach may use more memory as a struct might need only 4 byte alignment)
  3. I know we can define structs with higher alignment than 8 but if I am not doing so explicitly anywhere then is it safe to assume that any struct or pointer I use would have a maximum alignment of 8 bytes on a 64 bit linux system

Cheers, RG

EDIT: Instead of using char directly, I specified a struct to control the alignment.

1
1. The size of a pointer is not necessarily 8. 2. Um, what's slab? You're getting into placement new territory soon, which I don't think is what you want.Alexander Huszagh
Perhaps malloc uses the additional word for housekeeping or error detection?Raedwald
@Alexander, slab is just a preallocated buffer.RGs
@Raedwald, it could be a possible reason, but I would like to be sure.RGs
The vector type __m128 in the SSE instruction set needs 16 bytes alignment. I think the operator new makes 16 bytes alignment to avoid program crash in case the programmer stores a __m128 in the aligned memory block. But not all systems align allocated memory by 16.A Fog

1 Answers

0
votes

There is a tension between getting the perfect packing (no wasted space on allocation), ease of re-use of a chunk (less waste due to holes), speed, and code simplicity.

Only allocating 16-Byte-Aligned chunks which are an integral multiple of 16 Byte big might waste a bit of memory, but simplifies things considerably.