I have the following struct:
struct data {
char buffer[12];
bool flag;
}
When testing the size of the data
structure, I realized it was 16
bytes because of the boolean flag which added 3
bytes in padding. So I decided to do the following while using the last byte of the buffer
as the flag:
struct data {
char buffer[16];
}
This way my buffer
is 3
bytes larger for free as it would have been lost in padding anyway.
However, I want this structure to be platform independent, so I looked on cppreference and found the following (emphasis mine):
Every complete object type has a property called alignment requirement, which is an integer value of type size_t representing the number of bytes between successive addresses at which objects of this type can be allocated.
Based off this, I wrote the following:
struct data {
char buffer[12 + sizeof(size_t)];
}
It works on my device, but I am just wondering if this is guaranteed to properly align on all platforms and not waste any bytes?
Edit: I am aware that sizeof(size_t)
may be 8
bytes, making my structure 20
bytes. However, if the alignment is by 8
bytes, then my structure would be 20
bytes regardless. This is why I wish to know how the structure is aligned.