Structure Padding in C

Structure padding is extra unused bytes added by the compiler between structure members (or after the last member) to align them according to the CPU's memory access requirements.

Modern processors read/write data faster when it is properly aligned in memory (usually at addresses that are multiples of 2, 4, 8 bytes, depending on data type).

Improves performance (faster memory access)
Increases memory consumption
Not part of the data – purely compiler optimization

1. Why Does Padding Occur? (Alignment Rules)

Each data type has its natural alignment requirement (typically equal to its size):

Data TypeSize (bytes)Typical Alignment
char11 byte
short22 bytes
int / float44 bytes
double / long long88 bytes
pointers (most systems)4 or 84 or 8 bytes
Note: Compiler adds padding bytes so that each member starts at an address that is a multiple of its alignment requirement.

2. Classic Example of Structure Padding

C
Padding between members
#include <stdio.h>

struct Example1 {
    char a;      // 1 byte
    int b;       // 4 bytes
    char c;      // 1 byte
};

int main() {
    printf("Size of struct Example1: %zu bytes\n", sizeof(struct Example1));
    // Output: 12 bytes (not 6)
    return 0;
}

3. Another Common Real-World Example

C
Student record structure
struct Student {
    char name[20];   // 20 bytes
    int roll;        // 4 bytes
    char grade;      // 1 byte
    double gpa;      // 8 bytes
};

// Size = ? (usually 40 bytes on 64-bit system)

4. How to Avoid / Control Structure Padding

  1. Reorder members (largest to smallest size) – most effective & portable
  2. Use #pragma pack (compiler-specific)
  3. Use __attribute__((packed)) – GCC/Clang
  4. Use #pragma pack(1) / push/pop for selective control
C
Reducing padding by reordering + packed example
// Reordered (better) - usually 33 bytes
struct StudentOptimized {
    double gpa;
    int roll;
    char name[20];
    char grade;
};

// Packed (no padding) - 33 bytes
#pragma pack(1)
struct StudentPacked {
    char name[20];
    int roll;
    char grade;
    double gpa;
};
#pragma pack() // reset

5. When to Use Packed Structures?

  • Network programming (fixed packet formats)
  • Hardware registers / embedded systems
  • File formats / serialization (binary files)
  • Interfacing with legacy systems
  • Memory-critical applications