Structure Padding

  • Structure padding means adding extra bytes to the member of the structure.
  • The main reason for doing such alignment (placing the member at a particular location/address) is to optimize the performance of the processor in terms of reading and writing at a particular memory location.
  • Most modern processors will work efficiently when data is stored at an address that is multiple of its size.
  • For example, in the case of a 32-bit processor which reads 32 bits at a time, it will work efficiently when the data is stored at an address that is multiple of 4.
  • In general, the size of the structure is multiple of its largest members.
  • It’s always good practice to declare fields in structure either ascending or descending order of their size to minimize the waste of memory.
  • Structure padding can be disabled by #pragma pack(1)

Example:

#include <stdio.h>

struct abc
{
   char a;
   char b;
   int c;
}obj;

int main()
{
 printf("\n The size of the structure is: %d\n", sizeof(obj));
 return 0;
}
Output:
The size of structure is: 8   

Explanation:

If we overlook the concept of structure padding, the size of the structure would be char a(1) + char b(1) + int c(4) = Total of 6 bytes

Without structure padding, the processor will take 2 cycles to read the integer.

Memory alignment (without structural padding)

untitled image

Since it is a 32-bit machine hence in one cycle 4 bytes will read. So to access the integer it needs two cycles.

Memory alignment (with structural padding)

untitled image

Thus, the total size of the structure is char a(1 byte) + char b(1 byte) + 2 bytes(padding) + int c (4 bytes) = 8 bytes.

Thus, to access integer c, just one cycle is needed, increasing the optimization in accessing the member’s structure.

This is the significance of structure padding.

More examples:

struct example
{
   char a;
   short b;
   char c;
   long d;
   char e;
}obj;

Size is 1 + 2 +1 +4(padding) + 8 + 1 +7(padding) = 24 bytes. 
struct example
{
   long a;
   short b;
   char c;
   char d;
   char e;
}obj;

Size is 8 +2 +1 +1 +1 +3(padding) = 16 bytes;

Note:

We can use the pre-processor directive that is #pragma pack(1) to disable this structure padding.

Generic Syntax: #pragma pack(n)

where n is the alignment bytes and valid values are 1, 2, 4, 8 and the default value is 8.

Relevant Posts:



Categories: C Language

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: