Structure padding and packing

前端 未结 9 1224
太阳男子
太阳男子 2020-11-21 05:04

Consider:

struct mystruct_A
{
   char a;
   int b;
   char c;
} x;

struct mystruct_B
{
   int b;
   char a;
} y;

The sizes of the structur

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 05:37

    Rules for padding:

    1. Every member of the struct should be at an address divisible by its size. Padding is inserted between elements or at the end of the struct to make sure this rule is met. This is done for easier and more efficient Bus access by the hardware.
    2. Padding at the end of the struct is decided based on the size of the largest member of the struct.

    Why Rule 2: Consider the following struct,

    If we were to create an array(of 2 structs) of this struct, No padding will be required at the end:

    Therefore, size of struct = 8 bytes

    Assume we were to create another struct as below:

    If we were to create an array of this struct, there are 2 possibilities, of the number of bytes of padding required at the end.

    A. If we add 3 bytes at the end and align it for int and not Long:

    B. If we add 7 bytes at the end and align it for Long:

    The start address of the second array is a multiple of 8(i.e 24). The size of the struct = 24 bytes

    Therefore, by aligning the start address of the next array of the struct to a multiple of the largest member(i.e if we were to create an array of this struct, the first address of the second array must start at an address which is a multiple of the largest member of the struct. Here it is, 24(3 * 8)), we can calculate the number of padding bytes required at the end.

提交回复
热议问题