• In order to align the data in memory, one or more empty bytes are inserted or left blank between memory addresses which are allocated for other structure members while memory allocation. This theory is called structure padding.
• Architecture of a computer processor is such a way that it can read 1 word (4 byte in 32 bit processor) from memory at a time.
• To make use of this benefit of processor, data are always aligned as 4 bytes package which leads to insert empty addresses between other member’s address.
• Because of this structure padding concept in C, size of the structure is always not same as what we think.
For example 1:-
struct student
{
int id1;
int id2;
char a;
char b;
float percentage;
};
..
• As per C concepts, int and float data types occupy 4 bytes each and char datatype occupies 1 byte for 32 bit processor. So, only 14 bytes (4+4+1+1+4) should be allocated for above structure. But, this is wrong.
• I t takes 16 bytes (4+4+1+1+2 bytes padding+4).
This is because:-
1. Architecture of a computer processor is such a way that it can read 1 word from memory at a time.
2. One word is equal to 4 bytes for 32 bit processor and 8 bytes for 64 bit processor. So, 32 bit processor always reads 4 bytes at a time and 64 bit processor always reads 8 bytes at a time.
3. This concept is very useful to increase the processor speed.
4. To make use of this advantage, memory is arranged as a group of 4 bytes in 32 bit processor and 8 bytes in 64 bit processor.
.
Example 2:-
struct fun
{
char c;
short s;
void* p;
int i;
};
Memory aligned memory, for 32-bit:
< char >< pad >< pad >< pad > // 1 byte char, 3 bytes padding
< short >< pad >< pad > // 2 byte short, 2 bytes padding
< void* > // 4 bytes
< int > // 4 bytes
and thus sizeof(fun) == 16 Bytes.