I am using Linux 32 bit os,
and GCC compiler.
I tried with three different type of structure.
in the first structure i have defined only one char
variable. size of this structure is 1 that is correct.
in the second structure i have defined only one int
variable. here size of the structure is showing 4 that is also correct.
but in the third structure when i defined one char
and one int
that means total size should be 5, but the output it is showing 8. Can anyone please explain how a structure is assigned?
typedef struct struct_size_tag
{
char c;
//int i;
}struct_size;
int main()
{
printf("Size of structure:%d\n",sizeof(struct_size));
return 0;
}
Output: Size of structure:1
typedef struct struct_size_tag
{
//char c;
int i;
}struct_size;
int main()
{
printf("Size of structure:%d\n",sizeof(struct_size));
return 0;
}
Output: Size of structure:4
typedef struct struct_size_tag
{
char c;
int i;
}struct_size;
int main()
{
printf("Size of structure:%d\n",sizeof(struct_size));
return 0;
}
Output:
Size of structure:8
The difference in size is due to alignment. The compiler is free to choose padding bytes, which make the total size of a structure not necessarily the sum of its individual elements.
If the padding of a structure is undesired, because it might have to interface with some hardware requirement (or other reasons), compilers usually support packing structures, so the padding is disabled.
You definitely get Data Structure 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."
For more, take a look at this, Data Structure Alignment
The C standard allows a compiler to add padding bytes to structs after any field to allow the following field to be aligned according to any specific requirements of the compiler (or the user of the compiler). The standard does not specify, but typically a compiler will provide a command line argument to specify the (default) alignment. Good compilers also invariably support the de facto standard of #pragma pack, including push and pop options.
Padding bytes provide improved performance by reducing the amount of memory accesses required by suitably aligned data types. For example, on a 32-bit processor (more specifically a system which uses memory with 32 data lines) accessing a 32-bit integer will require two memory accesses when reading and writing the value rather than just one if it crosses a 4-byte boundary (ie, unless the bottom two bits of the address of the integer are zero).
See My Blog Post for more details (better than Wikipedia article).
The magic word is padding/memory alignment @see data structure alignment.