DEV Community

Cover image for Computer Science Challenge - Structure Padding
Harshita Sharma D
Harshita Sharma D

Posted on

Computer Science Challenge - Structure Padding

This is a submission for DEV Computer Science Challenge v24.06.12: One Byte Explainer.

Explainer

Structure padding: Like neatly lining books on a shelf, compilers add empty bytes (padding) between struct members for faster processor access. This can make structs larger than expected!

Additional Context

Consider this code:-

#include <iostream>

struct Data {
  char c; // 1 byte
  int i;  // 4 bytes (assuming 32-bit system)
};

int main() {
  std::cout << sizeof(Data) << std::endl; // Might be > 5!
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • This code defines a Data struct with a char and an int.
  • Similar to the previous example, we use sizeof(Data) to print the struct size. Here, padding might occur to ensure the int aligns with its preferred boundary (often 4 bytes on 32-bit systems).
  • The expected size would be 1 (char) + 4 (int) = 5 bytes. However, the actual size might be greater due to padding.
  • If you ask me, then it will be 8 bytes, since we are assuming a 32-bit system that will read the memory in the chunks of 4 bytes. This does not allow other variables to take the left 3 bytes (8-5) space. Hence 8 bytes will get occupied by the object of struct Data for faster processor access.

Note:

The exact amount of padding can vary depending on the compiler and target architecture.

Alan Turing the computer scientist explaining  the concept of structure padding in c++ pride month color palette rainbow color

  • This image is generated using the prompt:- "Alan Turing, the computer scientist, explaining the concept of structure padding in C++ pride month color palette rainbow color"

Top comments (0)