Padding and Packing in C Programming

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.

 

Let’s understand Padding and Packing in C with example:

Padding:

#include <iostream>

struct school
{
double a;
int b;
char h;
int c;
char d;
};

int main()
{
school students;

printf("size of struct: %d \n",sizeof(students));
return 0;

}

Output:

size of structure: 24

Memory Level Description

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

padding and packing in c

Example for Packing:

#include <iostream>

# pragma pack (1)
struct school
{
double a;
int b;
char h;
int c;
char d;
};

int main()
{
school students;

printf("size of struct: %d \n",sizeof(students));
return 0;

}

OUTPUT:

size of struct: 18

Memory Level Description

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

padding and packing in c

Discuss in comments in case of any query regarding padding and packing in C programming language.

Leave a Comment