Pages

Friday, February 13, 2015

What is Slack Byte in Structure


Computer stores structures using the concept of "word boundary". The Size of a word boundary is machine dependent. In computer with two bytes word boundary, the members of a structure are stores left aligned on the word boundary, as shown below. A character data takes one byte and an integer takes two bytes. One byte between them is left unoccupied. This unoccupied byte is known as the slack byte.

Also Read: What is Exception Handling in C++?
Also Read: What is Virtual Base Class in C++?

What is Slack Byte in Structure?

When we declare structure variables, each one of them may contain slack bytes and the values stored in such slack bytes are undefined. Due to this, even if the members of two variables are equal, their structure do not necessarily compare equal. C, therefore, does not permit compassion of structure. However, we can design our own function that could compare individual members to decide whether the structures are equal or not.

Observe the below program and try to run it.

#include<stdio.h>

struct demo
{
char ch;
float f;
};

void main()
{
struct demo d;
printf("Size=%d",sizeof(d));
}

What is Slack Byte in Structure?

If we assume size of char and float be 1 byte and 4 bytes respectively. Then according to this the size of structure variable d should be 5 (1+4) bytes. But as you can see in above image the output is 8 bytes. This shows that there are three bytes between them is left unoccupied which is known as slack bytes.

One thing we have to keep in mind that it is not always necessary that a structure variable contains slack bytes. 

It may be possible that I have missed something in above tutorial, so let me know about it by commenting below. If you liked above article then don’t forget to comment and share!!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.