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"

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay