class Data {
double a, b, c;
};
int main() {
Data x, y, z;
cout << sizeof(x) << endl;
cout << &x << " " << &y << " " << &z << endl;
}
The output of the above code was:
24
0x7ffd911f5640 0x7ffd911f5660 0x7ffd911f5680
Here's my question: The Data class object needs only 24 bytes of space, then why the compiler allocates 32 bytes (memory spaces between 0x7ffd911f5640 and 0x7ffd911f5660) for each object instead?
In C++, the memory alignment and padding are used to ensure efficient memory access, especially for types like double which might require specific alignment. This is why the memory allocated might seem more than the sum of the sizes of individual members of the class.
In your Data class, the total size might indeed sum up to 24 bytes (double a, double b, and double c). However, due to memory alignment and padding, the actual memory allocation might be larger to ensure proper alignment of the variables within the memory space, which can lead to a slight increase in the memory footprint.
The memory addresses observed (0x7ffd911f5640, 0x7ffd911f5660, 0x7ffd911f5680) indicate a difference of 0x20 (32 in decimal) between consecutive objects. This suggests an alignment or padding requirement of 8 bytes for each object, making each object take up 32 bytes in memory despite the actual size of Data being 24 bytes.
This padding is introduced by the compiler to ensure that the CPU can efficiently access the data in memory, especially when dealing with types that require specific alignments like double.