You copied the Doc URL to your clipboard.

__attribute__((packed)) type attribute

The packed type attribute specifies that a type must have the smallest possible alignment. This attribute only applies to struct and union types.


You must access a packed member of a struct or union directly from a variable of the containing type. Taking the address of such a member produces a normal pointer which might be unaligned. The compiler assumes that the pointer is aligned. Dereferencing such a pointer can be unsafe even when unaligned accesses are supported by the target, because certain instructions always require word-aligned addresses.


If you take the address of a packed member, in most cases, the compiler generates a warning.

When you specify __attribute__((packed)) to a structure or union, it applies to all members of the structure or union. If a packed structure has a member that is also a structure, then this member structure has an alignment of 1-byte. However, the packed attribute does not apply to the members of the member structure. The members of the member structure continue to have their natural alignment.

Example 3-2 Examples

struct __attribute__((packed)) foobar 
  char x;
  short y;

short get_y(struct foobar *s) 
    // Correct usage: the compiler will not use unaligned accesses
    // unless they are allowed.
    return s->y;

short get2_y(struct foobar *s) 
    short *p = &s->y; // Incorrect usage: 'p' might be an unaligned pointer.
    return *p;  // This might cause an unaligned access.