Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reasoning behind libc++'s 16-byte alignment pattern for std::basic_string?

While looking at the libc++ implementation of std::basic_string, I came across this in line 1374 (at the time of writing):

enum {__alignment = 16};

This value is used in subsequent alignment calculations, string size requests being rounded up to multiples of this number.

I can accept that some rounding is going on to avoid memory fragmentation or whatever, but...

I wonder if there is any specific rationale behind using a hardcoded 16 as the number here, or if it's just used as a "nice 'round' number".

For a 64-bit machine, 16 amounts to alignof( std::max_align_t ), and that makes some sort of sense. But the exact same value for __alignment is used for 32-bit architectures as well, so...?

like image 602
DevSolar Avatar asked May 21 '18 16:05

DevSolar


People also ask

Is malloc 16 byte aligned?

The GNU documentation states that malloc is aligned to 16 byte multiples on 64 bit systems.

How do you align bytes?

General Byte Alignment RulesStructures between 5 and 8 bytes of data should be padded so that the total structure is 8 bytes. Structures between 9 and 16 bytes of data should be padded so that the total structure is 16 bytes. Structures greater than 16 bytes should be padded to 16 byte boundary.

What is align in C++?

alignof and alignas The alignas type specifier is a portable, C++ standard way to specify custom alignment of variables and user defined types. The alignof operator is likewise a standard, portable way to obtain the alignment of a specified type or variable.


1 Answers

When I first designed <string>, libc++ wasn't yet destined to be open-source. I was writing for Apple's platforms only. And Apple's malloc always allocates at least 16 bytes, and in multiples of 16 bytes, no matter how much you ask for (at least this was true in 2007, I haven't checked recently).

So if the most commonly used allocator is going to hand you 16 bytes, you might as well use them in your capacity.

At one time, a few years earlier, I tried to change the allocator API so that it could ask the allocator how much memory it actually handed out for any particular request. But that attempt failed. So the next best thing was taking advantage of a-priori knowledge of the most common allocator the code was going to deal with.

like image 186
Howard Hinnant Avatar answered Oct 06 '22 10:10

Howard Hinnant