1

I have looked through a post of structure padding in geeksforgeeks, https://www.geeksforgeeks.org/is-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member/ But I don't know why in this case:

int main() 
{ 

    struct C { 
        // sizeof(double) = 8 
        double z; 

        // sizeof(short int) = 2 
        short int y; 
        // Padding of 2 bytes 

        // sizeof(int) = 4 
        int x; 
    }; 

    printf("Size of struct: %d", sizeof(struct C)); 

    return 0; 
} 

I know y (short int) is followed by x (int) and hence padding is required after y. But why the padding here is 2?

fuyao
  • 33
  • 1
  • 3
  • Architecture of a computer processor is such a way that it can read 1 word (4 byte in 32 bit processor) from memory at a time.1 word is equal to 4 bytes for 32 bit processor and 8 bytes for 64 bit processor. So, 32 bit processor always reads 4 bytes at a time and 64 bit processor always reads 8 bytes at a time. So 8+2+4+2=16 bytes thats 4 words. – VVish Apr 23 '19 at 05:00
  • The main rules are (1) it depends on the compiler — though the compiler is usually constrained by the ABI (application binary interface) for the platform — and (2) the compiler can't put padding at the beginning of the structure. There are multiple previous questions about the topic, too. – Jonathan Leffler Apr 23 '19 at 05:18

1 Answers1

2

The compiler wants to align int on a four-byte boundary, and it is two-bytes short of that, therefore the padding is calculated as two bytes:

struct C { 
    // offset = 0
    double z; 
    // offset = 8
    short int y; 
    // offset = 10
    // ... padding ...
    // offset = 12
    int x; 
    // offset = 16
}; 

The next multiple of four greater than 10 is 12.

EDIT: The structures are, in practice, aligned following this algorithm (pseudocode):

offset = 0;
alignment = 1;
for each field in structure {
    offset = (offset + field.alignment - 1) / field.alignment * field.alignment;
    field.offset = offset;
    alignment = lcm(alignment, field.alignment);
}
structure.alignment = alignment;
structure.size = (offset + alignment - 1) / alignment * alignment;
Yakov Galka
  • 70,775
  • 16
  • 139
  • 220