Reputation: 353
I'm confused by alignment requirement and word size. I'm working on a 64-bit processor, so the word size is 8, which means the allocated address should be a multiple of 8, right?
But alignof
gives me unexpected results.
struct A
{
int a;
char b;
}
Output:
sizeof(A): 8
alignof(A): 4 // why?
In comparison,
sizeof(double): 8
alignof(double): 8
If I happen to provide an address that is a multiple of 4 but not a multiple of 8 for A
, the performance will be lower because one more access, is that correct?
Is it because alignof()
provides the least requirement that we need to follow, while alignment on 8 bytes in this specific example is better with a simple memory-performance trade-off?
Upvotes: 1
Views: 1446
Reputation: 45654
The standard makes few guarantees with regard to alignment and general struct layout.
Among them:
Your example fulfills all of them. If you want, you can get a stronger alignment though (C++11):
struct alignas(8) A {
int a;
char b;
}
Also, just because the bitness of the processor is 64, that is not reflected in higher alignment requirements for most types, though stronger-aligned data can have better read/write performance.
You will only get worse performance if the weaker alignment means the data straddles more cache-lines and the processor must thus fetch more of them.
Upvotes: 2
Reputation: 21607
Some hardware systems prohibit unaligned memory accesses. Doing so causes an exception. This common in RISC processors.
Other processors take a performance hit. Often it takes two processor cycles to access unaligned data.
The reason for your results above is that your compiler is using a 4-byte int (not an 8-byte).
struct A
{
int a; // 4 bytes
char b; // 1 byte
// 3 bytes padding
}
Upvotes: 1
Reputation: 34563
Alignment requirements are platform-specific, but typically a primitive type's minimum alignment is the same as its size. The processor can do 32-bit load/store operations on any 32-bit boundary, but a 64-bit load or store requires 64-bit alignment.
Your structure's alignment is 4 because nothing within it requires 8-byte alignment. Though it only holds 5 bytes of meaningful data, its size is padded to 8 so that in an array, the second and subsequent instances will also be properly-aligned.
Upvotes: 1