0
0
CDebug / FixIntermediate · 3 min read

How to Avoid Structure Padding in C: Tips and Fixes

Structure padding in C happens because the compiler adds extra space to align data for faster access. To avoid padding, reorder fields from largest to smallest or use __attribute__((packed)) to tell the compiler not to add padding.
🔍

Why This Happens

Structure padding occurs because computers access memory faster when data is aligned to certain boundaries. The compiler adds extra unused space between fields to align them properly. This can cause the structure to take more memory than the sum of its fields.

c
struct Example {
    char a;
    int b;
    char c;
};

#include <stdio.h>
#include <stddef.h>

int main() {
    printf("Size of struct: %zu\n", sizeof(struct Example));
    printf("Offset of a: %zu\n", offsetof(struct Example, a));
    printf("Offset of b: %zu\n", offsetof(struct Example, b));
    printf("Offset of c: %zu\n", offsetof(struct Example, c));
    return 0;
}
Output
Size of struct: 12 Offset of a: 0 Offset of b: 4 Offset of c: 8
🔧

The Fix

To avoid padding, reorder the fields from largest to smallest type so the compiler can align them without gaps. Alternatively, use __attribute__((packed)) to tell the compiler not to add padding, but this may slow down access.

c
struct ExampleFixed {
    int b;
    char a;
    char c;
} __attribute__((packed));

#include <stdio.h>
#include <stddef.h>

int main() {
    printf("Size of packed struct: %zu\n", sizeof(struct ExampleFixed));
    printf("Offset of b: %zu\n", offsetof(struct ExampleFixed, b));
    printf("Offset of a: %zu\n", offsetof(struct ExampleFixed, a));
    printf("Offset of c: %zu\n", offsetof(struct ExampleFixed, c));
    return 0;
}
Output
Size of packed struct: 6 Offset of b: 0 Offset of a: 4 Offset of c: 5
🛡️

Prevention

Always order structure fields from largest to smallest type to minimize padding naturally. Use compiler-specific packing attributes only when necessary, as they can reduce performance. Use tools like offsetof and sizeof to check structure layout during development.

Enable compiler warnings or use static analysis tools to detect inefficient padding. Document your structure layouts clearly for future maintenance.

⚠️

Related Errors

Similar issues include:

  • Misaligned access errors: When the CPU requires aligned data but the structure is packed, causing crashes on some platforms.
  • Unexpected large structure sizes: Caused by poor field ordering leading to wasted memory.
  • Data corruption: When using packed structures without care, some CPUs may read/write data incorrectly.

Key Takeaways

Structure padding aligns data for speed but can waste memory.
Order fields from largest to smallest to reduce padding naturally.
Use __attribute__((packed)) carefully to remove padding but watch for performance hits.
Check structure sizes and offsets with sizeof and offsetof.
Avoid packing unless necessary and test on your target platform.