Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

06
Feb

Structure padding

Related Blog Items

What is padding in C?

All modern CPUs expect that the fundamental types — int’s, float’s and long’s — are stored in the memory at their natural boundary; typically, at addresses that are multiples of their length.  Some CPU work efficiently if the memory is properly aligned, and some can work in either case. 

For the following examples, let us assume:

sizeof (int)   == 4
sizeof (char)  == 1
sizeof (float) == 4

When a C compiler processes a structure, it adds padding bit(s)/byte(s), if required, between the members to ensure proper alignment.  Consider the following scenario:

Consider the following structure declaration:

struct pad1
{
int a;
char c;
float f;
};

In the above struct, "a" and "f" should occur at an address multiple of 4, whereas "c" can take any — odd or even — address.  So, the structure appears in the memory as shown:

 ___________________
| a0 | a1 | a2 | a3 |      4-byte alignment
 ——————-       P is padding byte
| c0 | P0 | P1 | P2 |
 ——————-
| f0 | f1 | f2 | f3 |
 ——————-

Consider this structure:

struct pad2
{
float f;
int a;
char c;
};

 ___________________
| f0 | f1 | f2 | f3 |      4-byte alignment
 ——————-       P is padding byte
| a0 | a1 | a2 | a3 |
 ——————-
| c0 | P0 | P1 | P2 |
 ——————-

Following point are worth noting:

  • The compiler also ensures that the structure as a whole appears at an aligned address
  • Padding does NOT occur at the beginning of a structure
  • The value of padding bytes or bits are implementation defined

Uses of padding:

  • Padding is useful, for example, in conforming to externally imposed layouts of machine registers
  • The obvious advantage is efficient access by CPU
  • For some architecture, padding is mandatory as the CPU cannot read misaligned datum.  Usually results a "bus error"

Popularity: 18%

You need to log on to convert this article into PDF


Related Blog Items

No Comments

No comments yet.

Leave a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-spam image