Using attribute((packed))
What you'll learn: How to tell the compiler to remove extra "padding" bytes from structures to save space or match specific data formats.
The invisible gaps
When you define a struct, you might assume the size of the structure is simply the sum of its parts. However, CPUs prefer to read data from memory addresses that are multiples of 4 or 8. To help the CPU run faster, the compiler automatically inserts invisible "padding" bytes between your variables to keep them aligned.
Imagine a row of parking spots. A large truck (an int) must start at a spot numbered 4, 8, or 12. If a small motorcycle (a char) takes spot 1, the truck won't fit in spot 2 or 3; the compiler leaves those spots empty and puts the truck in spot 4. This is efficient for the CPU, but it wastes space.
Forcing a tight fit
Sometimes, you don't want these gaps. If you are writing data to a file that another program will read, or if you are communicating with hardware that expects a very specific sequence of bytes, you need the data to be "packed" tightly together.
In GCC and Clang, we use __attribute__((packed)) to tell the compiler: "No gaps. Put these variables exactly next to each other, even if it makes the CPU work a little harder."
#include <stdio.h>
// A standard struct (usually 8 bytes due to 3 bytes of padding)
struct NormalStruct {
char a; // 1 byte
int b; // 4 bytes
};
// A packed struct (exactly 5 bytes)
struct PackedStruct {
char a;
int b;
} __attribute__((packed));
int main() {
printf("Normal size: %zu bytes\n", sizeof(struct NormalStruct)); // Likely 8
printf("Packed size: %zu bytes\n", sizeof(struct PackedStruct)); // Exactly 5
return 0;
}
When to use it
Packing is a trade-off. While it saves memory, accessing unaligned data can slightly slow down your program because the CPU might need two memory reads instead of one to grab a single integer.
Use __attribute__((packed)) when you are:
- Matching a specific binary file format.
- Sending data over a network where every byte counts.
- Interfacing with hardware registers that have no "gaps."
Key takeaway
The __attribute__((packed)) directive instructs the compiler to eliminate padding bytes, creating a smaller, dense structure at the cost of potential performance overhead.