Why the concept of padding is added only when there are multiple members of a structure and why is it not included when there is a single basic data type member ?
if we consider on a 32bit machine
struct
{
char a;
} Y;
There is no padding and sizeof Y comes to 1 byte .
If we consider this structure
struct
{
char a;
int b;
} X;
Sizeof X will be 8bytes .
My question is Why was padding adding in the second case ? If it is for efficient access by the machine which normally reads data in blocks of multiples of 4bytes then why was there no padding in the first case ?
Structure padding is a concept in C that adds the one or more empty bytes between the memory addresses to align the data in memory.
structure A short int is 2 byte aligned. If the short int element is immediately allocated after the char element, it will start at an odd address boundary. The compiler will insert a padding byte after the char to ensure short int will have an address multiple of 2 (i.e. 2 byte aligned).
Compilers are free to insert padding between fields, and following the final field (but not before the first field). This is usually done for performance as some types perform better when they're aligned on specific boundaries.
Padding increases the performance of the processor at the penalty of memory. In structure or union data members are aligned as per the size of the highest bytes member to prevent the penalty of performance.
Padding is added in the second case because, on your machine, an int
is aligned to 4 bytes. So it has to reside at an address that is divisible to 4.
0x04 0x05 0x06 0x07 0x08 0x09 0x0A 0x0B
a b b b b
If no padding is added, the int
member starts at address 0x05
, which is wrong. With 3 added padding bytes:
0x04 0x05 0x06 0x07 0x08 0x09 0x0A 0x0B
a | padding | b b b b
Now the int
is at 0x08
, which is OK.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With