What is padding in structure?

In C++, a structure is like a bookshelf with different shelves holding different kinds of books. Each shelf represents a piece of information, such as a number or a letter.

Now, picture the computer trying to arrange these shelves neatly in its memory, just like placing books on a bookshelf. However, there’s a rule: books should be put in specific spots, like every 4th spot or every 8th spot.

Padding in C++, it’s like arranging our bookshelves in a way that the computer can easily find and use the information, following its own set of rules. It’s similar to placing extra cushions on the bookshelf to make sure everything stays organized.

Let’s discuss the example of padding in programming.

Example of padding in struct

In C++, padding refers to the insertion of empty bytes between the members of a structure. The purpose of padding is to align the members in memory for more efficient access by the computer’s hardware.

Memory alignment

  • Computers often access memory more efficiently when data is aligned on certain byte boundaries (like 44 bytes or 88 bytes).

  • To achieve this alignment, the compiler may insert empty bytes (padding) between the members of a structure.

struct example

  • Imagine a structure with two members: an integer (44 bytes) and a character (11 byte).

  • Without padding, the total size would be 55 bytes, but to align it on a 44-byte boundary, the compiler may insert 33 bytes of padding after the character.

struct Example {
int number; // 4 bytes
char letter; // 1 byte
}; // Total size: 8 bytes (including padding)

Let’s visualize the struct example mentioned above:

Struct padding example
Struct padding example

Let’s write down a complete code below and check the sizes of each member:

#include <iostream>
using namespace std;
struct Example {
int number; // 4 bytes
char letter; // 1 byte
};
int main() {
// Print the size of the structure
cout << "Size of Example structure: " << sizeof(Example) << " bytes" << std::endl;
// Print the size of each member to analyze padding
cout << "Size of int: " << sizeof(int) << " bytes" << std::endl;
cout << "Size of char: " << sizeof(char) << " bytes" << std::endl;
return 0;
}

Code explanation

  • Line 4–8: We define a structure named Example with two members: an integer number (44 bytes) and a character letter (11 byte).

  • Line 11: We print the size of the structure ( 88 bytes). The compiler will fill 33 bytes of padding.

  • Line 14–15: We print the size of each member to analyze the padding.

Copyright ©2024 Educative, Inc. All rights reserved