STRUCTURE PADDING

Structure padding mainly talks about memory for variables which are aligned based on the size of the variable. Let suppose a “char” of 1 byte memory can be assigned anywhere in between like 0x1000 to 0x1001. Same way if we have an “int” of 4 bytes memory can be assigned anywhere in between like 0x1004 to 0x1008. This structure padding concept is automatic for its member are byte aligned by the compiler.

Structure padding is nothing but allocating more memory for a structure than required and that extra bytes are called as padded bytes.

This structure padding happens of number of bytes accessed by the CPU per CPU cycle.

Before introducing this structure padding Concept ,CPU used to get 1 byte of memory per CPU cycle. This is one of the disadvantages.

Imagine I have Below Structure with me

struct demo

{

char a;

int b;

float c;

};

Total size of this structure(without structure padding) is 9 bytes.

In order to allocate 9 bytes It needs 9 CPU cycle. To avoid this problem

Structure padding concept came into picture.

In structure padding , It will look for largest member and Per CPU cycle it can access that many bytes of Memory.

Consider above Example, largest member is int and float both are bytes, so per CPU cycle it will get 4 bytes of memory.

It will allocate memory just like above figure. So here 3 empty bytes are called as padded bytes and This is how structure padding happens.

Let us consider one more Example,

struct  demo

{

char ch;

double d;

int a;

};

Here largest member is double so per CPU cycle it will get 8 bytes of mem

Now, structure padding happens as shown in above diagram and here 11 bytes are getting wasted. When large amount of memory is getting wasted, It will be a drawback. Then we need to avoid structure padding.

Inorder to avoid structure padding we need perform structure packing. That means we need to pack one byte at a time.

We can do it in two ways

  1. #pragma pack(1)
  2. __attribute__((__packed__))

We can use these two instructions with structure to avoid structure padding.

For example,

1.

#pragma pack(1)

struct  demo

{

char ch;

double d;

int a;

};

2.

struct  demo

{

char ch;

double d;

int a;

}__attribute__((__packed__));

This about the structure padding. This can be both advantage and disadvantage. So we need to han

Enquire Now

Enquire Now

Enquire Now

Please Sign Up to Download

Please Sign Up to Download

Enquire Now

Please Sign Up to Download

Enquiry Form