Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alignas in structs on 32-bit platforms

I am getting unexpected results when running the following code for 32-bit x86 linux (compiler flags: g++ -std=c++14 -m32). I tried gcc and clang.

#include <iostream>
using namespace std;

struct S1
{
  uint64_t a;
  uint32_t b;
};

struct S2
{
  alignas(uint64_t) char a[8];
  uint32_t b;
};

int main()
{
  cout << "sizeof(S1)=" << sizeof(S1) << endl;
  cout << "sizeof(S2)=" << sizeof(S2) << endl;
}

The output is:

sizeof(S1)=12
sizeof(S2)=16

What is happening here? Why are S1 and S2 of different size? As I understand it, 64 bit integer values are aligned to 32 bit on 32-bit x86 machines. This does explain why the size of S1 is 12 bytes. But why does this not apply to S2?

like image 272
user3809741 Avatar asked Jan 06 '16 13:01

user3809741


Video Answer


1 Answers

The alignof keyword measures the alignment of a type as a complete object; i.e. when it is allocated as an individual object or array element. This is not necessarily the same as the alignment requirements of that type as a subobject; Are members of a POD-struct or standard layout type guaranteed to be aligned according to their alignment requirements?

The alignment of a 64-bit integer within a struct is mandated by the x386 ABI at 4 bytes; gcc is not at liberty to change this, as it would break binary compatibility with other object files and programs. However, it can align complete-object 64-bit integers to 8 bytes, as doing so does not affect the ABI, and makes for more efficient access to memory.

like image 187
ecatmur Avatar answered Oct 06 '22 05:10

ecatmur