Home > database >  Reducing memory alignment
Reducing memory alignment

Time:04-01

I want to know if it is possible to "reduce" the alignment of a datatype in C . For example, the alignment of int is 4; I want to know if it's possible to set the alignment of int to 1 or 2. I tried using the alignas keyword but it didn't seem to work.

I want to know if this is something not being done by my compiler or the C standard doesn't allow this; for either case, I would like to know the reason why it is as such.

CodePudding user response:

I want to know if it is possible to "reduce" the alignment of a datatype in C .

It is not possible. From this Draft C Standard:

10.6.2 Alignment specifier      [dcl.align]


5     The combined effect of all alignment-specifiers in a declaration shall not specify an alignment that is less strict than the alignment that would be required for the entity being declared if all alignment-specifiers appertaining to that entity were omitted.

The 'reason' for this is that, in most cases, alignment requirements are dictated by the hardware that is being targeted: if a given CPU requires that an int be stored in a 4-byte-aligned address then, if the compiler were allowed to generate code that puts such an int in a less strictly aligned memory location, the program would cause a hardware fault, when run. (Note that, on some platforms, the alignment requirement for an int is only 1 byte, even though access may be optimized when more strictly aligned.)


Some compilers may offer ways that appear to allow alignment reduction; for example, MSVC has the __declspec(align(#)) extension, which can be applied in a typedef statement. However, from the documentation: __declspec(align(#)) can only increase alignment restrictions:

#include <iostream>
typedef __declspec(align(1)) int MyInt; // No compiler error, but...
int main()
{
    std::cout << alignof(int) << "\n";   // "4"
    std::cout << alignof(MyInt) << "\n"; // "4" ...doesn't reduce the aligment requirement
    return 0;
}
  • Related