0

Suppose I have the following Foo class. The size of Foo's member variables are what I would expect. However, the size of Foo it'self is 16. Where are the extra four bytes coming from?

#include <iostream>
#include <string>

using namespace std;

class Foo {
public:
        int *data;
        int length;
};

int main() {
        Foo f;
        cout << "Size of foo's data: " << sizeof(f.data) << endl;
        cout << "Size of foo's length: " << sizeof(f.length) << endl;
        cout << "Size of foo: " << sizeof(f) << endl;

        return 0;
}

Output:

        Size of foo's data: 8 
        Size of foo's length: 4 
        Size of foo: 16 
ChrisD
  • 674
  • 6
  • 15

2 Answers2

2

You're seeing the evidence of otherwise-"invisible" padding bytes that the compiler has added (in this case, to the end of your class) to achieve alignment.

Compilers like to align structures on convenient (e.g. 64 bits, or 8 bytes, in your case) boundaries for more efficient access to their members. This is true in this case if you were to create an array of multiple Foo objects; the end padding would keep the start of each one on an 8-byte (64-bit) boundary. If you had varying sizes of fields within this class, you might also see additional padding between the fields for the same purpose.

Ben Zotto
  • 70,108
  • 23
  • 141
  • 204
  • Interesting. So there would be no need for the compiler to add padding if I were to add another int member variable, making Foo's size a multiple of 8? – ChrisD Feb 22 '15 at 06:07
  • 1
    @ChrisD: Good followup question. Maybe, but the compiler may well want to add padding to *both* `int` fields in that case, so that any access to a field would be 8-byte-aligned the same way, making your class 24 bytes in size. It depends. :) Compilers are allowed a fair bit of latitude for this sort of layout, you should try it and see what happens. You can also check the address of each member to see how closely spaced they are. – Ben Zotto Feb 22 '15 at 06:11
  • 1
    Very cool. Yeah, when I added another int, the size of my Foo object went to 16. Also, when printing the addresses, they were 8-byte-aligned as you said. Thanks for your insight. – ChrisD Feb 22 '15 at 06:21
1

The compiler can add padding to align words, that's probably where it's coming from. You can use #pragma pack to try to eliminate it, but I'm not certain that's reliable