Byte Padding

Hi,

Can someone explain what is byte padding?

For ex:
struct emp{
char s;
int b;
char s1;
int b1;
long b3;
char s3;
}

What will be the size of this structure?

Thanks

Check for the sizeof operator like:

#include <stdio.h>

typedef struct{
char s;
int b;
char s1;
int b1;
long b3;
char s3;
}emp;

void main() {
emp tst1;
printf ("Size: %d\n", sizeof(tst1));
}

Output at my machine:

Size: 24

Padding is implementation dependent. Basically it means the the objects inside the struct have their beginning addresses moved (padded with bytes) so the start of each object can be accessed by the hardware efficiently.

Misalignment of objects can result in a SIGBUS core dump, or very much slower access to the object. Some compilers have a pragma to turn off or alter padding. Others provide warnings about padding.

for gcc try to define your structure like this:

struct gtpp_hdr6 {
unsigned char flag; // 1 byte
unsigned char message_type; // 1 byte
unsigned short length; // 2 bytes
unsigned short sequence; // 2 bytes
} __attribute__((__packed__));

and check again.
This attribute shows compiler that this structure used for data packets and compiler will not do padding

Its actually low level issue. Padding stores all the data element started from even addresses. In this mechanism char also take 2 bytes ( one Byte stored in current even address, next data element can store in next even address, in b/w odd address is wasted). But it improves data reading efficiency.

Hi,
When working in many client/server situations that data being passed is passed in data structures. It's important to know the padding arrangements between two architects, so here is an example program that shows how to see the offsets.
#include <stdio.h>
int main (void)
{
struct {
char a;
int i;
double d;
} st;

printf ("st size: %d\noffset a: %d\noffset i: %d\noffset d:%d\n",
sizeof (st),
((char *) (&st.a)) - ((char *)&st),
((char *) (&st.i)) - ((char *)&st),
((char *) (&st.d)) - ((char *)&st));

}

C compilers on different systems lay out structures differently.
In some cases there can even be layout differences between different
C compilers on the same system. Compilers add gaps between fields,
and these gaps have different sizes and are at different locations.
You can normally assume that there are no gaps between fields of type char
or array of char. However, you can not make any assumptions about
gaps between fields of any larger type. You also can not make any
assumptions about the layout of bitfield types.

(From autobook 1.5)