Structure members are placed one after another in the increasing order of memory. Now a CPU with 32bit data bus width is optimized to access 32bit or 4byte at a time and thus compiler arranges structure members in such a way that it maintains 32bit memory alignment. For 64bit this alignment is 64bit or 8bytes. Structure packing and padding extra bytes in structure members comes into picture.

Packing is an option in compiler to define how the members of a structure will be aligned in memory. It is defined via pre-processor #pragma pack(). For 32bit compiler pack(4) is default and similarly for 64bit pack(8) is default. Now we are instructing compiler to align members in 4byte memory spaces then what happen when we have some members with size less than 4. Here comes padding in picture. Some extra bytes are used by compiler to pad these gaps. Pack(1) is called tight packing. We do not have any type less than 1byte size thus this means no padding for pack(1).

#pragma pack(1)
struct pack_test_t {
  unsigned char m_byte;
sizeof(struct pack_test_t) is 1

#pragma pack(4)
struct pack_test_t {
  unsigned char m_byte;
sizeof(struct pack_test_t) is 4 [sizeof(m_byte) + sizeof(3 padding bytes)]

You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.

 Vote 0

Similar topics related to this section

user defined types, typedef, struct type, union type, struct vs union, struct pack padding, size of a structure, bit fields, l-value, struct and array,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan