After much time spent on the internet to find the answer, I didn't get anything.
My question is this: I have a 64-bit system and when I run this code:
#include<iostream>
using std::cout;
class A
{
char a ; //1
char b ; //1
int c; //4
int d; //4
};
int main()
{
A a1;
cout<<sizeof(a1);
return 0;
}
the output is 12, not 16. Why?
CodePudding user response:
In the used system sizeof( int )
is equal to 4
. So to align the data member c
the compiler pads 2
bytes after the variable b
. As a result the size of the structure is 12 bytes.
You could get a more visible result dependent on whether a 32
or 64
bit system is used if you would declare data members c
and d
having the type long
. In most 64-nit systems sizeof( long )
is equal to 8
.
CodePudding user response:
Padding bytes are added between data members of a structure or class when they are needed to either fulfil the alignment requirements of any of those data members, or (more generally) to optimize access speed to those members.
Now, although the alignment requirements for types such as int
are not specified by the C Standard, and can vary (or not vary) between 32-bit and 64-bit builds for the same underlying chip (such as the Intel x86-64 systems), the alignment requirement for the char
type (and also signed char
and unsigned char
) is specified by the Standard! From cppreference:
The weakest alignment (the smallest alignment requirement) is the alignment of
char
,signed char
, andunsigned char
, which equals 1; the largest fundamental alignment of any type is implementation-defined and equal to the alignment ofstd::max_align_t
(since C 11).
So, as the alignment requirement for the b
member is 1, no padding is required between a
and b
. In your case, the alignment requirement for int
is 4 bytes, so two padding bytes must be added before the c
member. Thus, 2 × sizeof(char)
(= 2) 2 padding bytes 2 × sizeof(int)
(=8) gives a total size of 12 bytes.