Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alignof(char) == 1?

Tags:

c++11

sizeof(char) is always 1 and it seems to me that the alignment requirement of a type can never be larger than its size. Quoting from the upcoming C++11 standard (3.11):

An aligment is an implementation-defined integer value representing the number of bytes between successive addresses at which a given object can be allocated.

So if the alignment of a type were greater than its size, it would not be possible to create arrays without empty space between consecutive elements.

Is this interpretation correct and is thus alignof(char) == 1 always?

like image 241
bluescarni Avatar asked Aug 25 '11 13:08

bluescarni


People also ask

What does alignof do in c++?

alignof operator in C++ In C++11 the alignof operator used to returns the alignment, in bytes of the specified type. Syntax Explanation: alignof: operator returns the alignment in byte, required for instances of type, which type is either complete type, array type or a reference type.

Is malloc always aligned?

Since malloc (or another dynamic memory allocator) is not necessarily guaranteed to align memory as we require, we'll need to perform two extra steps: Request extra bytes so we can returned an aligned address.


1 Answers

You are correct.

You can infer from the "compact" (no padding) layout of C++ arrays that any object type such that an array of this type can be defined must have an alignment that is a divisor of its size.

In particular, the alignment of such a type of size 1 must be 1.

In particular, the alignment of char, signed char, and unsigned char is 1.

OTOH, you cannot infer anything about the alignment of an abstract class with this argument.

like image 154
curiousguy Avatar answered Nov 12 '22 17:11

curiousguy