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__));
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__));