Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is padding added for multiple data members of structures and not for single members?

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 ?

like image 916
Laavaa Avatar asked Oct 12 '12 14:10

Laavaa


People also ask

What is the purpose of data structure padding?

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.

Why is padding used when storing structure elements?

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).

Why does the compiler insert padding between fields?

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.

What is the advantage of structure padding in C?

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.


1 Answers

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.

like image 63
Luchian Grigore Avatar answered Sep 23 '22 20:09

Luchian Grigore