For example, consider the following:
Suppose int is 4-byte aligned and long is 8-byte.
struct example { int a; long b; int c; };
The obvious way for the compiler to put this in memory would be: AAAAPPPPBBBBBBBBCCCCPPPP with the whole structure having 8-byte alignment.
- P refers to fill byte
- A refers to byte
- B refers to byte b
- C refers to byte c
In this case, sizeof (example) is 24.
but another way to do this would be as follows: AAAABBBBBBBBCCCCCC with the whole structure having alignment, so the address of the initial byte mod 8 = 4 (not sure how to say it more briefly)
in this case, you do not need to fill, so you save 8 bytes per instance.
My question is, are compilers allowed to do this (by standard)? Do they really do it? I always saw that alignment was discussed simply in bytes.
c ++ memory-alignment
Bwmat
source share