Course contentsShow
← C
Lesson 642 of 1,2199. Structures and UnionsFree lesson

The `__attribute__((packed))` directive

The __attribute__((packed)) directive

What you'll learn: How to tell the compiler to remove invisible gaps in your structures to save memory and match specific data formats.

The Secret Gaps

Computers are picky about how they read data. To make things run faster, the CPU prefers data to be "aligned"—usually at even addresses like 4 or 8 bytes. Because of this, C compilers often insert invisible "padding" bytes between your struct members.

Imagine you have a struct with a char (1 byte) followed by an int (4 bytes). Instead of taking up 5 bytes, the compiler might insert 3 empty "padding" bytes after the char so the integer starts on a fresh 4-byte boundary. Your struct is now 8 bytes! Usually, this is good for speed, but if you are sending data over a network or talking to hardware, those extra hidden bytes will scramble your communication.

Using the "Packed" Directive

To stop the compiler from adding this extra space, we use a special GCC/Clang instruction: __attribute__((packed)). This tells the compiler: "Forget about speed; squeeze these variables as tightly as possible."

#include <stdio.h>

// A standard struct with padding
struct Standard {
    char a;     // 1 byte
    // 3 bytes of invisible padding here!
    int b;      // 4 bytes
};

// A packed struct with NO padding
struct Packed {
    char a;
    int b;
} __attribute__((packed));

int main() {
    printf("Standard size: %zu bytes\n", sizeof(struct Standard)); // Likely 8
    printf("Packed size: %zu bytes\n", sizeof(struct Packed));     // Exactly 5
    return 0;
}

When to Use It

Think of a packed struct like a suitcase where you’ve sat on the lid to close it. Everything is tightly squeezed together. You should use this when:

  1. Network Protocols: You need to match a header format (like an IP packet) exactly bit-for-bit.
  2. Binary Files: You are reading a file created by another system that doesn't use the same padding rules.
  3. Memory-Constrained Hardware: You are working on a tiny chip where every single byte of RAM is precious.

Just be careful: because the CPU has to work harder to read "unaligned" data, your program might run a tiny bit slower. Use it only when the exact layout of memory matters more than raw speed.

Key takeaway

The __attribute__((packed)) directive removes all padding between struct members, ensuring the total size is the sum of its parts.