Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the alignment of char in C (and C++) guaranteed to be 1? [duplicate]

Can the alignof(char) be anything but 1?

From the unofficial cppreference.com wiki:

The weakest (smallest) alignment is the alignment of the types char, signed char, and unsigned char, and it is usually 1.

The "usually" seems to imply that it could be something else.

The only thing the C standard stipulates regarding the alignment of char is (C11 N1570 6.2.8 paragraph 1):

The alignment requirement of a complete type can be queried using an _Alignof expression. The types char, signed char, and unsigned charshall have the weakest alignment requirement.

However, consider the definition of alignment (C11 N1570 6.2.8 paragraph 1, and defined similarly for C++11):

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

From this, I don't think it makes sense for the alignment of char to be anything but 1 due to the requirement that sizeof(char) ≡ 1, which implies the distance between adjacent char elements can only be 1 byte.

Does this make sense?

like image 814
Rufflewind Avatar asked Apr 23 '16 01:04

Rufflewind


1 Answers

Yes. Although this statement is not explicitly specified in the standards, I suppose it can inferred from them:

N1570 6.5.3.4 The sizeof and _Alignof operators

4 When sizeof is applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1. When applied to an operand that has array type, the result is the total number of bytes in the array.

Taking char for example. Say we have an char charArr[2];. sizeof charArr is guaranteed to be 2, and sizeof charArr[0] = sizeof charArr[1] = 1. This means two adjacent char objects take the place of 2 bytes.

Consequently, it can be inferred that "the number of bytes between successive addresses at which a char can be allocated" is at least 1. Also, the alignment of char must be a positive integer, so it can't be any number other than 1.

like image 121
nalzok Avatar answered Sep 25 '22 03:09

nalzok