user3156285
user3156285

Reputation: 353

alignment and word size

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

Answers (3)

Deduplicator
Deduplicator

Reputation: 45654

The standard makes few guarantees with regard to alignment and general struct layout.

Among them:

  • All alignments are powers of 2.
  • A structure has no smaller alignment-requirement than its most-aligned sub-object. (trivial)
  • The size of a struct is a multiple of its alignment (also trivial, else arrays would be impossible)

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

user3344003
user3344003

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

Wyzard
Wyzard

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

Related Questions