What is Structure Packing?
Sometimes it is mandatory to avoid padded bytes among the members of the structure. For example, reading contents of ELF file header or BMP or JPEG file header. We need to define a structure similar to that of the header layout and map it. However, care should be exercised in accessing such members. Typically reading byte by byte is an option to avoid misaligned exceptions but there will be a hit on performance.
Most of the compilers provide nonstandard extensions to switch off the default padding like pragmas or command line switches. Consult the documentation of the respective compiler for more details.
In GCC, we can use the following code for structure packing:
#pragma pack(1)
or
struct name { ... }__attribute__((packed));
Example of Structure Packing
C
// C Program to demonstrate the structure packing #include <stdio.h> #pragma pack(1) // structure A typedef struct structa_tag { char c; short int s; } structa_t; // structure B typedef struct structb_tag { short int s; char c; int i; } structb_t; // structure C typedef struct structc_tag { char c; double d; int s; } structc_t; // structure D typedef struct structd_tag { double d; int s; char c; } structd_t; int main() { printf ( "sizeof(structa_t) = %lu\n" , sizeof (structa_t)); printf ( "sizeof(structb_t) = %lu\n" , sizeof (structb_t)); printf ( "sizeof(structc_t) = %lu\n" , sizeof (structc_t)); printf ( "sizeof(structd_t) = %lu\n" , sizeof (structd_t)); return 0; } |
sizeof(structa_t) = 3 sizeof(structb_t) = 7 sizeof(structc_t) = 13 sizeof(structd_t) = 13
Structure Member Alignment, Padding and Data Packing
In C, the structures are used as data packs. They don’t provide any data encapsulation or data hiding features.
In this article, we will discuss the property of structure padding in C along with data alignment and structure packing.