Why padding are added, if char comes after int?
In this case
char
comes afterint
and no need to add padding bytes, it meanssizeof(A) = 5
byte, but in this case I also get the8
byte result. Why ?
First you need to understand why padding is needed?
Wiki says that:
Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding. When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system) or larger. Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory. To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.
To make the size multiple of 4
(alignment of int
) , the second snippet will be padded with 3
bytes. After compilation the second snippet will be padded for proper alignment as
struct A
{
int i;
char a;
char Padding[3]; // 3 bytes to make total size of the structure 8 bytes
};
EDIT: Always remember these two golden rules of structure padding:
- Padding is only inserted when a structure member is followed by a member with a larger alignment requirement or at the end of the structure.
- The last member is padded with the number of bytes required so that the total size of the structure should be a multiple of the largest alignment of any structure member.
In case of
struct s
{
int b;
double c;
char a;
};
alignment will take place as
struct s
{
int b; // 4 bytes. b is followed by a member with larger alignment.
char Padding1[4]; // 4 bytes of padding is needed
double c; // 8 bytes
char d; // 1 byte. Last member of struct.
char Padding2[7]; // 7 bytes to make total size of the structure 24 bytes
};
Also note that by changing the ordering of members in a structure, it is possible to change the amount of padding required to maintain alignment. This can be done by if members are sorted by descending alignment requirements.
struct s
{
double c; // 8 bytes
int b; // 4 bytes
char a; // 1 byte. Only last member will be padded to give structure of size 16
};