Struct packing and alignment help organize data in memory efficiently. It ensures data fits well and works fast on the computer.
Struct packing and alignment in Embedded C
struct MyStruct {
char a;
int b;
char c;
} __attribute__((packed));The __attribute__((packed)) tells the compiler not to add extra spaces between fields.
Without packing, the compiler may add padding to align data for faster access.
struct Normal {
char a;
int b;
char c;
};struct Packed {
char a;
int b;
char c;
} __attribute__((packed));b to be aligned on an 8-byte boundary.struct Aligned {
char a;
int b __attribute__((aligned(8)));
char c;
};This program shows the difference in size and field positions between a normal struct and a packed struct. It prints the total size and the byte offset of each field.
#include <stdio.h> #include <stddef.h> struct Normal { char a; int b; char c; }; struct Packed { char a; int b; char c; } __attribute__((packed)); int main() { printf("Size of Normal struct: %zu\n", sizeof(struct Normal)); printf("Size of Packed struct: %zu\n", sizeof(struct Packed)); printf("Offset of a in Normal: %zu\n", offsetof(struct Normal, a)); printf("Offset of b in Normal: %zu\n", offsetof(struct Normal, b)); printf("Offset of c in Normal: %zu\n", offsetof(struct Normal, c)); printf("Offset of a in Packed: %zu\n", offsetof(struct Packed, a)); printf("Offset of b in Packed: %zu\n", offsetof(struct Packed, b)); printf("Offset of c in Packed: %zu\n", offsetof(struct Packed, c)); return 0; }
Packing structs can save memory but may slow down access on some processors.
Alignment helps the CPU read data faster by placing it on certain memory boundaries.
Use packing carefully when working with hardware or network protocols that require exact data layouts.
Struct packing removes extra spaces between fields to save memory.
Alignment adds spaces so data is placed on boundaries for faster access.
Use packing and alignment to control how data is stored and accessed in memory.