5
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?

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
  • 4
    What compiler, what platform, what options? In [this test](https://godbolt.org/z/sP4qMsGGv) `gcc -O2` gives 32 bytes each but several other compilers (`clang -O2`, `icc -O2`) give only 24. `gcc -Os` also gives 24. – Nate Eldredge Mar 23 '21 at 03:55
  • 5
    The [32-byte](https://godbolt.org/z/c8xebEGvn) allocation for `Data` is observed when using `gcc` with the default options. The allocation is reduced to (the expected) [24 bytes](https://godbolt.org/z/WqaT3T14E) when turning off SSE instructions with `-mno-sse`. This suggests that the extra 8-byte padding is done to align `Data` addresses to 16-bytes, as required by SSE instructions, though it's not clear why it would do that in the very simple case here. – dxiv Mar 23 '21 at 04:15
  • 1
    @dxiv I'd assume that it always aligns structs full of `double`s for SSE, even if nothing *in this* translation unit warrants that, because who knows what *other* translation units see that declaration. – Caleth Mar 23 '21 at 09:10

0 Answers0