Search code examples
cstructpaddingmemory-alignmentlong-double

Alignment when using a long double in a structure


I know in general, a struct instance will have the alignment of its widest scalar member. I declared a structure having a member of long double data type.

struct try
{
    char a;
    long double b;
};
struct try obj;

When i tried to check sizeof(obj) it is coming out as 16. My compiler assumes long double as 12 bytes. So i am not able to understand how exactly padding is being done here and how alignment is happening in structure. I assumed that alignment will be done on basis of long double as it is the widest scalar member. So there should be a 11 byte padding for char and the size of structure variable should come out as 24 but output is 16. So exactly what is happening here ?. I am working on a 64 bit processor.


Solution

  • First of all, your compiler is creating 32-bit output even though you have a 64-bit processor. Anyway, you're assuming that things need to be aligned to a boundary identical to their size, which isn't true in general. In particular, in your case, long doubles take up 12 bytes, but only need to be aligned to a 4-byte boundary. As such, after your single-byte char, the compiler inserts 3 bytes of padding to get to a 4-byte boundary, and then inserts your 12-byte long double. 1+3+12 is 16, so struct try is 16 bytes long.