0
#include<iostream>
using namespace std;
class phone{
    char a;
    int c;
    char b;
};
int main(void)
{
    phone obj;
    cout<<sizeof(obj);
}

Why the output is 12 instead of 8??? I'm using a 64-bit machine and GCC 4.9.2 64-bit release.

  • Three bytes after `a` (to align `c`) and 3 bytes at the end (to align the overall structure). – Adrian Mole Apr 09 '22 at 11:24
  • why the compiler needs to align c? Is the cpu not reading 8 bytes at a time? – MD. RAISUL ISLAM RIFAT 1902081 Apr 09 '22 at 11:27
  • Looks like for your computer it reads 4 bytes at a time, and that's why everything is aligned to 4. `c` must be padded, because otherwise some other structure (that happens to be allocated next to a `phone` object) could get misaligned. – Yksisarvinen Apr 09 '22 at 12:01
  • 1
    Even if your computer read eight bytes at a time, we typically would want a four-byte `int` to have an alignment requirement of four bytes. If it could be placed at an offset of, say, two bytes relative to a multiple of eight, then an array of `int` objects would have elements at offsets 2, 6, 10, 14, 18, and so on. The machine can read that first element with one read, by doing the eight-byte read of bytes 0-7 and using the `int` in bytes 2, 3, 4, 5. But it would have to do two reads for that next element, doing reads of bytes 0-7 and 8-15 to get the `int` in bytes 6, 7, 8, and 9. – Eric Postpischil Apr 09 '22 at 12:27
  • move `c` up and the size will become 8. It's always recommended to sort fields in descending order of size to reduce the padding – phuclv Apr 09 '22 at 13:47

0 Answers0