Anil Katti
Anil Katti

Reputation: 1313

Use of struct padding

What is the use of padding struct in C?

Upvotes: 5

Views: 1968

Answers (2)

ChrisF
ChrisF

Reputation: 137188

See this Wikipedia article for more information, but basically it's to make sure that the struct occupies an exact number of bytes - which as Steve314 states means that sizeof is an exact multiple of the alignment.

Data alignment means putting the data at a memory offset 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.

You should also know that while this was very important for a programmer to know about this, it's become less so now because it is often handled by the compiler for you. There will be compiler options that allow you to control the process though.

Upvotes: 4

Carl Norum
Carl Norum

Reputation: 225172

Some architectures will perform better if only aligned accesses are made, so putting 32-bit objects on 32-bit boundaries, and 64-bit objects on 64-bit boundaries can improve the speed of your application.

Some architectures are completely incapable of making unaligned accesses, and on those architectures not padding can be a real disaster.

Upvotes: 13

Related Questions