0
0
Embedded Cprogramming~5 mins

Struct packing and alignment in Embedded C

Choose your learning style9 modes available
Introduction

Struct packing and alignment help organize data in memory efficiently. It ensures data fits well and works fast on the computer.

When you want to save memory by removing extra spaces between data fields.
When communicating with hardware or devices that expect data in a specific format.
When sending data over a network where size matters.
When reading or writing binary files with a fixed layout.
When you want to control how your data is arranged in memory for speed.
Syntax
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.

Examples
This struct may have padding bytes added by the compiler for alignment.
Embedded C
struct Normal {
    char a;
    int b;
    char c;
};
This struct has no padding; fields are packed tightly.
Embedded C
struct Packed {
    char a;
    int b;
    char c;
} __attribute__((packed));
This struct forces b to be aligned on an 8-byte boundary.
Embedded C
struct Aligned {
    char a;
    int b __attribute__((aligned(8)));
    char c;
};
Sample Program

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.

Embedded C
#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;
}
OutputSuccess
Important Notes

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.

Summary

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.