🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Free C Programming Course · Structure and Union
Structure Padding and sizeof
Understand why sizeof a structure is bigger than its members, predict padding with three simple rules, and shrink structures on small microcontrollers.
What You Will Learn
- Why alignment and padding exist
- The three rules the compiler uses to place members
- How member order changes structure size, shown with real output
- When and how to use packed structures safely
Prerequisites
- Structure memory layout (previous lecture)
- Sizes of C data types
Structure Padding in C Explained
Structure padding in C is the reason sizeof on a structure often gives a bigger number than the sum of its members. Compilers insert invisible filler bytes so that each member sits at an address the processor can read efficiently. This is one of the most asked topics in embedded interviews, and it directly affects RAM usage on small microcontrollers. In this free embedded C programming lecture you will learn why padding exists, how to predict it, how to shrink it, and how to switch it off when a wire format demands it.
Why Padding and Alignment Exist
Processors fetch memory in aligned chunks. A 4-byte integer at an address that is a multiple of 4 can be loaded in one bus access. The same integer at an odd address may need two accesses, run slower, or on some cores such as certain Cortex-M0 parts raise a hard fault. To avoid this, the compiler follows an alignment requirement for each type: usually a type is aligned to its own size, up to the machine’s maximum.
| Type | Typical size | Typical alignment (x86-64 / Cortex-M4) |
|---|---|---|
char | 1 | 1 |
short | 2 | 2 |
int, float | 4 | 4 |
double, long long | 8 | 8 on x86-64, 8 on Cortex-M4 by the ABI |
| pointer | 8 on 64-bit, 4 on Cortex-M | same as size |
Older books describe this with the rule that integers sit only at even addresses. That was true on some 16-bit machines. Today the multiple-of-size rule is the usual one, so do not memorise a fixed number of padding bytes; learn the method instead.
The Three Rules the Compiler Follows
- Each member is placed at the next offset that is a multiple of that member’s alignment.
- The whole structure’s alignment equals the largest alignment among its members.
- The total size is rounded up to a multiple of the structure’s alignment. This adds trailing padding, so arrays of the structure keep every element aligned.
Measuring Padding with a Program
The program compares three structures. bad and good contain the same three members in a different order. wire is the same as bad but marked packed, a GCC and Clang extension that removes padding.
#include <stdio.h>
#include <stddef.h>
struct bad { char a; int b; char c; };
struct good { int b; char a; char c; };
struct pair { char c; int n; };
struct __attribute__((packed)) wire { char a; int b; char c; };
int main(void)
{
printf("sum of members (bad) = %zu\n", sizeof(char) + sizeof(int) + sizeof(char));
printf("sizeof(struct pair) = %zu\n", sizeof(struct pair));
printf("sizeof(struct bad) = %zu\n", sizeof(struct bad));
printf("sizeof(struct good) = %zu\n", sizeof(struct good));
printf("sizeof(struct wire) = %zu\n", sizeof(struct wire));
printf("bad: a=%zu b=%zu c=%zu\n", offsetof(struct bad, a), offsetof(struct bad, b), offsetof(struct bad, c));
printf("good: b=%zu a=%zu c=%zu\n", offsetof(struct good, b), offsetof(struct good, a), offsetof(struct good, c));
_Static_assert(sizeof(struct good) == 8, "layout changed");
return 0;
}
gcc -std=c11 -Wall -Wextra -o c1 c1.c
./c1
Expected output:
sum of members (bad) = 6
sizeof(struct pair) = 8
sizeof(struct bad) = 12
sizeof(struct good) = 8
sizeof(struct wire) = 6
bad: a=0 b=4 c=8
good: b=0 a=4 c=5
Walk through bad using the rules. a (1 byte) goes at offset 0. b needs alignment 4, so it jumps to offset 4, leaving 3 bytes of padding. c (1 byte) goes at offset 8. The structure’s alignment is 4, so 9 bytes round up to 12, adding 3 bytes of trailing padding. Only 6 of the 12 bytes carry data. In good, the large member comes first, the two chars sit next to each other, and only 2 bytes of trailing padding are needed: total 8.
Reducing Padding by Reordering Members
The cheapest fix is free: declare members from the largest alignment to the smallest. Put pointers and double values first, then int, then short, then char. On a part with 8 KB of RAM and an array of 100 records, saving 4 bytes per record frees 400 bytes, which can decide whether a feature fits.
Tip: lock the result in
Add _Static_assert(sizeof(struct good) == 8, "layout changed"); next to the definition, exactly as the program above does. Anyone who adds a member and silently grows the structure gets a build error right away.
Packed Structures: Use With Care
When a structure must match a byte-exact external format, such as a network header or a sensor’s register dump, you can ask for no padding. GCC and Clang accept __attribute__((packed)); IAR and Keil have equivalent pragmas. In the program, struct wire shrinks to 6 bytes.
| Approach | Size | Speed | Portable | Best for |
|---|---|---|---|---|
| Natural layout | Larger | Fastest | Yes | General program data |
| Reordered members | Smaller | Fastest | Yes | Large arrays of records on small RAM |
| Packed attribute | Smallest | Slower or may fault | Compiler specific | Fixed binary formats you cannot change |
| Manual serialisation | Exact | Small cost | Yes | Network and storage formats |
Real-World Use Cases
- RAM budgeting. Event queues, task control blocks and sensor logs are arrays of structures. Padding multiplies by the array length.
- Binary protocols. A 6-byte on-wire header must be 6 bytes, not 8 or 12.
- Cache efficiency. Smaller structures put more records in each cache line on application processors.
Common Mistakes and Troubleshooting
| Mistake | Result | Fix |
|---|---|---|
| Hand-adding member sizes to get the structure size | Buffers too small, memory corruption | Use sizeof everywhere |
| Assuming the same size on PC and target | Code that works on the desktop breaks on the board | Test with the target compiler, add static assertions |
Comparing structures with memcmp | Padding bytes differ even when members are equal | Compare member by member |
| Packing a structure and passing member addresses around | Misaligned access fault | Copy the member to a local variable first |
Best Practices and Performance
- Order members from widest to narrowest unless a hardware layout forces another order.
- Verify with
sizeof,offsetofand_Static_assert. - Use GCC’s
-Wpaddedwarning once to see where the compiler adds padding. - Prefer explicit serialisation over packed structures for data that leaves your device.
Worked Exercise: Predict, Then Verify
Try this on paper before reading the answer. Consider this structure on a platform where short is 2 bytes, int is 4 and double is 8 with 8-byte alignment (x86-64 or Cortex-M with the standard ABI):
struct t { char a; short b; char c; int d; };
Apply the rules. a sits at offset 0. b needs alignment 2, so it moves to offset 2 (one padding byte at offset 1). c goes at offset 4. d needs alignment 4, so it moves to offset 8 (three padding bytes). The total is 12, already a multiple of 4. Now reorder it as int d; short b; char a; char c;: the members land at offsets 0, 4, 6 and 7, and the size is a tidy 8. A second example with a double:
struct u { char a; double d; short s; char b; }; /* 24 bytes */
struct u2 { double d; short s; char a; char b; }; /* 16 bytes */
The first is 24 bytes because d jumps to offset 8, s sits at 16, b at 18, and the size rounds up to the next multiple of 8. The reordered version is 16 bytes. Compile a program that prints sizeof for each and confirm. On this lecture’s test machine the output was:
t size=12 a=0 b=2 c=4 d=8
t2 size=8
u size=24
u2 size=16
Finding Padding with the Compiler
You do not have to calculate by hand for every structure. Compile with gcc -Wpadded -c file.c and GCC reports each place where it inserts padding and how many bytes. Use it as a review tool on your own headers, then reorder the worst offenders. Remember that the warning is informational; some padding is required and harmless.
Key Takeaways
- Each member starts at a multiple of its alignment; the structure size is a multiple of its largest alignment.
- Reordering members largest to smallest usually removes padding.
- Packed structures save RAM but risk slow or faulting access.
- Never compare structures with memcmp; padding bytes are indeterminate.
- Always verify with sizeof and static assertions on the real target.
Frequently Asked Questions
What is structure padding in C?
Structure padding is the unused bytes the compiler inserts between members, and after the last member, so each member starts at an address suitable for its type.
Why is sizeof a structure larger than the sum of its members?
Because of padding. The compiler aligns each member and rounds the total size up to a multiple of the structure’s alignment.
How do I reduce structure size without losing data?
Reorder members from largest to smallest alignment, or choose smaller types where the value range allows it.
What does __attribute__((packed)) do?
It tells GCC or Clang to remove padding from the structure. The structure becomes smaller, but member access can be slower or fault on strict-alignment CPUs.
Is the size of a structure the same on all platforms?
No. It depends on the CPU, the ABI and compiler options. Check it on the target with sizeof.
Is trailing padding always added?
Only when needed to make the total size a multiple of the structure’s alignment, so that every element of an array of the structure stays aligned.
Keep Learning C for Embedded Systems
This lecture is part of our free embedded C programming course. Practice every program on your own machine, then move on to the next lecture.

1 Comment