What is padding? How we can avoid padding in data structures?

Structure padding is adding extra bits at the end, so that the structure completes the word boundary.

Computer memory is usually aligned to a boundary equal in size to the system word size. On a hypothetical 32-bit system, imagine that this word size is four bytes long. In the C language, you can create structures that store data. In order to align them to the word size, the C compiler may add padding to the structure. You can remove this padding by using a preprocessor directive that tells it to align data differently.

Following is the way to disable structure padding using pragma in C.
#pragma pack(push, 1)
//Define your structure here
#pragma pack(pop)
//Structure padding is re enabled.

Some compilers (GNU c) don’t support #pragma directive __attribute__((__packed__)) using this structure padding can be avoided.

 An example of how you would do this is below.
           struct sample
                         unsigned char m1 __attribute__((__packed__));
                         unsigned short m2 __attribute__((__packed__));
                         unsigned long m3 __attribute__((__packed__));

  Another way to achieve the same is as shown below:
           struct sample
                         unsigned char m1;
                         unsigned short m2;
                         unsigned long m3;
           } __attribute__((__packed__));

1 comment:

  1. Hi Man,

    Great info! I recently came across your blog and have been reading along.
    I thought I would leave my first comment. I don’t know what to say except that I have

    I am working on opening
    a door with my Pi3, I have borrowed a lot of this code so far,as to I am very new to programming. I have this much working, now i want a text message when door opens and closes. I have installed Twilio and with the simple code
    Python Code: (Double-click to select all)
    6 from twilio.rest import Client
    client = Client("ACxxxxxxxxxxxxxx", "zzzzzzzzzzzzz")

    body="Hello from Python!")

    Very useful article, if I run into challenges along the way, I will share them here.

    Ajeeth Kapoor