Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of struct padding

Tags:

c

padding

struct

What is the use of padding struct in C?

like image 403
Anil Katti Avatar asked Jan 03 '11 19:01

Anil Katti


People also ask

Why is struct padding needed?

The answer to that lies in how a CPU accesses memory. Typically a CPU has alignment constraints, e.g. a CPU will access one word at a time, or a CPU will require data to be 16byte aligned, etc. So to make sure that data is aligned according to the constraints of the CPU, padding is required.

Can we avoid structure padding?

In Structure, sometimes the size of the structure is more than the size of all structures members because of structure padding. Note: But what actual size of all structure member is 13 Bytes. So here total 3 bytes are wasted. So, to avoid structure padding we can use pragma pack as well as an attribute.


2 Answers

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.

like image 51
Carl Norum Avatar answered Sep 27 '22 21:09

Carl Norum


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.

like image 30
ChrisF Avatar answered Sep 27 '22 23:09

ChrisF