structure padding and packing in c example

Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding. When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system) or larger. Data alignment means putting the data at a memory address equal to some multiple of the word size, which increases the system’s performance due to the way the CPU handles memory. To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.

What is Padding

  • In order to align the data in memory,  one or more empty bytes (addresses) are inserted (or left empty) between memory addresses which are allocated for other structure members while memory allocation. This concept is called structure padding.
  •  Architecture of a computer processor is such a way that it can read 1 word (4 byte in 32 bit processor) from memory at a time.
  • To make use of this advantage of processor, data are always aligned as 4 bytes package which leads to insert empty addresses between other member’s address.
  • Because of this structure padding concept in C, size of the structure is always not same as what we think.

What is Packing

Packing, on the other hand prevents compiler from doing padding means remove the unallocated space allocated by structure.

  • In case of Linux we use __attribute__((__packed__))  to pack structure.
  • In case of Windows (specially in Dev c++) use  # pragma pack (1) to pack structure.

Example:-

1. In case of Padding of Structure

Program

Output

padding and packing in c

Memory Level Description

Size of Structure is 24 .Due to Padding all char variable are also assigned 4 bytes.

memory layout of structure with padding

2. In case of Packing of Structure

Program

Output

padding and packing in c

Memory Level Description

Size of Structure is 18. When padding is removed then memory is assigned according to the size of variable.

memory layout of structure without padding

Suggested Readings