What is structure padding in C?


Before the padding concept, a clear view about the memory alignment is required.
32bit processor means it can process 32 bits (or 4bytes) at one clock cycle. Same in case of 64 bit process means it can process 64 bits (or 8 bytes)  at one clock cycle.
1 word is 4 bytes in 32 bit processor.
1 word is 8bytes in 64 bit processor.
Data stored in memory must be aligned according to the length of the data.
If data length/size is 1 byte-can go at any address.
If data length/size is 2 bytes – address must be even number.
If data length/size is 4 bytes- address must be divisible by 4.
If data length/size is 8 bytes- address must be divisible by 8.
Now the concept of memory alignment is clear.
When the processor align the data in memory, one or more empty bytes are inserted between memory addresses, this is called padding. when memory allocated for structure members then extra bytes are inserted between memory address ,this concept is called structure padding.
Because of this structure padding concept in C, size  of the structure is always same as what we think.
For example:-
struct  structure1
{
       char name;
       char c;
       int i;
};
As  per C concept, int data type occupies 4 bytes each and char data type occupies 1 byte for 32 bit processor. So, size of the structure is 6 bytes(1+1+4).
But this is wrong ,why??
Actual size is 8 byte because two extra padding gaps are added [2+2(padding gap)+4].




No comments

Is a unit doublet function an even function or odd function?

Dirac’s delta function is defined by the following property  δ(t) = 0 at t !=0            ∞ at t=0. The derivative of an even fu...