Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a "packed" structure in C?

I am going though some C code written for the Microchip C30 compiler and I often see structs defined as follows:

typedef struct __attribute__((__packed__))  {     IP_ADDR     MyIPAddr;               // IP address     IP_ADDR     MyMask;                 // Subnet mask     IP_ADDR     MyGateway;              // Default Gateway         // etc... } APP_CONFIG; 

What does packed mean?

like image 285
PICyourBrain Avatar asked Mar 29 '11 13:03

PICyourBrain


People also ask

What is packed structure in C?

Generally packed structures are used: To save space. To format a data structure to transmit over network without depending on each architecture alignment of each node of the network.

What does packed structure mean?

The term "closest packed structures" refers to the most tightly packed or space-efficient composition of crystal structures (lattices). Imagine an atom in a crystal lattice as a sphere. While cubes may easily be stacked to fill up all empty space, unfilled space will always exist in the packing of spheres.

What is structure padding and packing in C?

Structure packing is only done when you tell your compiler explicitly to pack the structure. Padding is what you're seeing. Your 32-bit system is padding each field to word alignment. If you had told your compiler to pack the structures, they'd be 6 and 5 bytes, respectively.


2 Answers

When structures are defined, the compiler is allowed to add paddings (spaces without actual data) so that members fall in address boundaries that are easier to access for the CPU.

For example, on a 32-bit CPU, 32-bit members should start at addresses that are multiple of 4 bytes in order to be efficiently accessed (read and written). The following structure definition adds a 16-bit padding between both members, so that the second member falls in a proper address boundary:

struct S {     int16_t member1;     int32_t member2; }; 

The structure in memory of the above structure in a 32-bit architecture is (~ = padding):

+---------+---------+ | m1 |~~~~|   m2    | +---------+---------+ 

When a structure is packed, these paddings are not inserted. The compiler has to generate more code (which runs slower) to extract the non-aligned data members, and also to write to them.

The same structure, when packed, will appear in memory as something like:

+---------+---------+ | m1 |   m2    |~~~~ +---------+---------+ 
like image 56
Juliano Avatar answered Oct 12 '22 22:10

Juliano


It instructs the compiler to not add any padding between members of the struct.

See, for example, this page.

like image 43
NPE Avatar answered Oct 12 '22 22:10

NPE