As per my knowledge, By default 4-byte alignment will be done. say
typedef struct
{
int data7;
unsigned char data8;
//3 -bytes will be added here.
}Sample1;
so sizeof(Sample1)
will be 8.
But for the following structure, why padding is not happened?.
typedef struct
{
unsigned char data1;
unsigned char data2;
unsigned char data3;
unsigned char data4;
unsigned char data5;
unsigned char data6;
}Sample2;
But the sizeof(Sample2) is 6 only. This Sample2 is not a 4 byte aligned structure?
EDIT::
As per Wiki
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.
But members of Sample2 will not be aligned in multiples of two right??
Thanks.
None of the fields in your second struct require 4-byte alignment. unsigned char
only needs 1-byte alignment. Therefore, there is no need to actually align it to 4 bytes.
Structs are generally only aligned to the maximum alignment of all the fields.
data7
is a 4-byte item, so the compiler will normally attempt to align it to an address that's a multiple of 4.
data1
is a one-byte item, so the compiler won't try to align it to any particular boundary (i.e., there would be no real gain from doing so).
No, in a typical implementation Sample2
is not a 4-bute aligned structure. It is a 1-byte aligned structure.
In a typical implementation, the alignment requirement of the whole structure is calculated as the maximum of the alignment requirement of its individual members. This is why your Sample1
has alignment requirement of int
(4 on your platform), and your Sample2
has alignment requirement of unsigned char
, which is 1.
Char requires 1 byte alignment. The max data type there is char ,
which is one byte alignment hence you are getting the size as '6'.
You can check this site for more understanding. http://www.geeksforgeeks.org/archives/9705.
They have explained it in detail.