views:

87

answers:

1

what is mean by slack byte in structures in C. please help.

+7  A: 

Usually padding bytes to ensure that data is aligned correctly. For example:

struct x {
    int a;     // four bytes
    char b;    // one byte
               // three bytes slack
    int c;     // four bytes
} xx;

will probably have slack bytes between b and c to get c aligned on a correct boundary.

You can check this by seeing what sizeif(xx) gives you (12 in the case above although it depends on the implementation).

Some architectures run slower if they have to use (for example) a four byte value that isn't aligned on a four-byte boundary. Some architectures won't allow that at all, instead generating an exception.

paxdiablo
mohit
@mohit, probably not between a and b since char most likely can be aligned on a 1-byte boundary. If the int was two bytes, there would probably only be 1 byte of slack after b.
paxdiablo
@pax thanx alot.
mohit
one more doubt, is slack byte always present in structures, or it is some special cases.
mohit
**Most** architectures won't allow it at all. The exception just happens to be the most common architecture, x86.
R..
@mohit, the only case where there are no padding bytes is when the elements of your structure naturally align. Most good programmers designing structures that will be used as part of a library API (where you have to worry about compatibility between versions, etc.) will take care that the structure is naturally aligned. Microsoft is notorious for not having done so and instead using nonstandard 'pack' directives to the compiler to force it to generate misaligned structure elements.
R..