Reading history

Structure Padding and Alignment in C (sizeof, offsetof, pack)

5 min read 1 views

Understand structure padding in C: alignment, why sizeof is larger than the sum of members, offsetof, reordering members to save memory, and #pragma pack.

Add up the sizes of a structure’s members and you will often get a smaller number than sizeof reports. The difference is padding: unused bytes the compiler inserts so that each member sits at an address the processor can read efficiently. Understanding padding helps you save memory, predict structure sizes in interviews and avoid bugs when structures are written to files or sent over a network.

In this lesson you will learn

  • What alignment is and why processors need it
  • How padding is inserted between and after members
  • Measuring layout with offsetof and _Alignof
  • Reordering members to shrink a structure
  • Packed structures and their trade-offs

Seeing the Padding

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

struct Bad {       /* members in a poor order */
    char a;
    int  b;
    char c;
    double d;
    char e;
};

struct Good {      /* largest members first */
    double d;
    int    b;
    char   a;
    char   c;
    char   e;
};

int main(void) {
    printf("sizeof(char)=%zu int=%zu double=%zu\n", sizeof(char), sizeof(int), sizeof(double));
    printf("struct Bad : %zu bytes\n", sizeof(struct Bad));
    printf("  offsets a=%zu b=%zu c=%zu d=%zu e=%zu\n",
           offsetof(struct Bad, a), offsetof(struct Bad, b), offsetof(struct Bad, c),
           offsetof(struct Bad, d), offsetof(struct Bad, e));
    printf("struct Good: %zu bytes\n", sizeof(struct Good));
    printf("  offsets d=%zu b=%zu a=%zu c=%zu e=%zu\n",
           offsetof(struct Good, d), offsetof(struct Good, b), offsetof(struct Good, a),
           offsetof(struct Good, c), offsetof(struct Good, e));
    printf("alignof(double) = %zu\n", _Alignof(double));
    return 0;
}

Output (typical 64-bit system)

sizeof(char)=1 int=4 double=8
struct Bad : 32 bytes
  offsets a=0 b=4 c=8 d=16 e=24
struct Good: 16 bytes
  offsets d=0 b=8 a=12 c=13 e=14
alignof(double) = 8
  • Most types have an alignment requirement: an int usually starts at an address divisible by 4 and a double at one divisible by 8. Aligned data can be loaded in a single operation; misaligned data is slower or, on some processors, causes a crash.
  • In struct Bad, a takes byte 0, then 3 padding bytes push b to offset 4. After c at offset 8, 7 bytes of padding move d to 16. After e at 24, the structure is padded to 32 so its total size is a multiple of its largest alignment (8). That way every element of an array of these structs stays aligned.
  • Only 1 + 4 + 1 + 8 + 1 = 15 bytes hold data; 17 bytes are padding.
  • struct Good holds the same members ordered from largest to smallest. They pack tightly, and only 1 byte of padding at the end is needed: 16 bytes in total, half the size.
  • offsetof (from <stddef.h>) gives a member’s position in bytes, and _Alignof (C11) gives a type’s alignment.

Packed Structures

#include <stdio.h>

struct Normal { char tag; int value; };

#pragma pack(push, 1)
struct Packed { char tag; int value; };     /* no padding: GCC/Clang/MSVC extension */
#pragma pack(pop)

int main(void) {
    printf("Normal: %zu bytes, Packed: %zu bytes\n", sizeof(struct Normal), sizeof(struct Packed));
    struct Normal arr[10];
    printf("array of 10 Normal: %zu bytes\n", sizeof arr);
    return 0;
}

Output

Normal: 8 bytes, Packed: 5 bytes
array of 10 Normal: 80 bytes
  • #pragma pack(push, 1) tells GCC, Clang and MSVC to use no padding until #pragma pack(pop). The structure shrinks from 8 to 5 bytes. GCC also supports __attribute__((packed)).
  • Packing is not part of standard C. Accessing misaligned members is slower, can fault on some architectures, and taking the address of a packed member is risky. Use it only to match an external binary format, and prefer reading such formats byte by byte.
  • Padding multiplies in arrays: 10 structs of 8 bytes take 80 bytes, 30 of them padding. Reordering members is the free, portable way to save that memory.

Rules of Thumb

RuleReason
Order members from largest to smallest alignmentMinimises gaps
Group small members (chars, bools) togetherThey can share one padded block
Never assume sizeof equals the sum of membersPadding is compiler- and platform-specific
Do not write raw structs to files for other systemsPadding and byte order may differ
Use memset or = {0} before copying structs outPadding bytes may contain leftover data

Common Mistakes

  1. Comparing structs with memcmp; padding bytes may differ even when all members are equal.
  2. Writing structs directly to a file with fwrite and reading them on another compiler or system (see reading and writing structures to a file).
  3. Packing everything for small savings and losing performance.
  4. Answering interview questions without stating the platform; sizes such as 4 for int are typical, not guaranteed.

Practice Exercises

Exercise 1. On a typical 64-bit system, what is sizeof of struct { char a; double b; char c; }, and how would you reduce it?

Show answer

24 bytes: a at 0, 7 bytes padding, b at 8, c at 16, then 7 bytes of tail padding. Reordering to { double b; char a; char c; } gives 16 bytes.

Exercise 2. Print the offset of every member of a struct of your choice using offsetof.

Show answer
#include <stddef.h>
struct S { short s; long l; char c; };
printf("%zu %zu %zu %zu\n", offsetof(struct S, s), offsetof(struct S, l),
       offsetof(struct S, c), sizeof(struct S));   /* typically 0 8 16 24 */

Frequently Asked Questions

Can the compiler reorder my structure members to save space?

No. C requires members to appear in memory in the order they are declared, and the first member to be at offset 0. Only you can reorder them.

Does padding exist in unions?

A union is as large as its largest member, rounded up to its strictest alignment, so it can have padding at the end.

Summary

  • Compilers add padding so members are aligned for fast access.
  • Structure size is rounded up to a multiple of its largest alignment.
  • Ordering members from largest to smallest reduces padding.
  • Packing removes padding but is non-standard and can be slow.

Next: C Project: Student Records.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *