乐闻世界logo
搜索文章和话题

How do structure alignment and memory padding work in C language?

2月18日 17:22

How do structure alignment and memory padding work in C language?

Memory Alignment Principles:

  1. Alignment Rules

    • Structure members align to their natural boundaries
    • char: 1-byte alignment
    • short: 2-byte alignment
    • int: 4-byte alignment
    • double: 8-byte alignment (64-bit systems)
  2. Structure Total Size

    • Must be a multiple of its largest member size
    • May require padding bytes at the end

Example Analysis:

c
struct Example1 { char c; // 1 byte + 3 bytes padding int i; // 4 bytes }; // Total size: 8 bytes struct Example2 { char c1; // 1 byte + 1 byte padding short s; // 2 bytes int i; // 4 bytes }; // Total size: 8 bytes struct Example3 { char c1; // 1 byte + 7 bytes padding double d; // 8 bytes char c2; // 1 byte + 7 bytes padding }; // Total size: 24 bytes

Optimization Techniques:

  1. Member Ordering Optimization

    • Arrange members in descending size order
    • Reduce padding byte waste
  2. Using Compiler Directives

    c
    #pragma pack(1) // 1-byte alignment struct Packed { char c; int i; }; #pragma pack() // Restore default alignment
  3. Bit Field Usage

    c
    struct BitField { unsigned int a : 3; // 3 bits unsigned int b : 5; // 5 bits };

Important Notes:

  • Alignment rules may vary across platforms
  • Excessive packing can affect access performance
  • Consider byte order and alignment for network transmission
标签:C语言