Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Sizeof gives unpredictable results [duplicate]

Possible Duplicate:
Why does ‘sizeof’ give wrong measurement?

I have a structure called CBUFFER_PEROBJECT:

struct CBUFFER_PEROBJECT
{
    D3DXMATRIX Final;
    D3DXMATRIX Rotation;
};

And in another class I do this:

...
bd.ByteWidth = sizeof(CBUFFER_PEROBJECT); 
...

I found out that the size of D3DXMATRIX is 64, so 64+64 = 128 (right?). But my compiler is playing tricks with me (Visual C++), because as I was debugging the program, the bd.ByteWidth became 132, so I went to the Immediate Window (Visual Studio), and typed:

sizeof(D3DXMATRIX) + sizeof(D3DXMATRIX)

And the result was:

128

But the bd.ByteWidth became 132, and when I type the following into the "Immediate Window":

sizeof(CBUFFER_PEROBJECT)

It gives me:

128
like image 569
Miguel P Avatar asked Dec 16 '22 15:12

Miguel P


1 Answers

Right, you are confusing D3DMATRIX and D3DXMATRIX (note extra X in the second type). The first one is a plain matrix of 16 float values (so exactly 64 bytes). The latter is a class, and it obviously has 4 bytes of extra data somewhere in the structure. Perhaps a vtable or some such.

If you compile the code as C rather than C++, the size will be the same, as the header-file providing the latter of the structures then does typedef D3DMATRIX D3DXMATRIX;.

See: D3DXMATRIX and D3DMATRIX

Edit: This is a bit like the old joke about the military saying "If the map and reality doesn't match up, the map is right". In this case, if you don't agree with the compiler, you are wrong. The compiler is ALWAYS right when calculating sizes. Understanding WHY the compiler got that number, well, that's a different matter... Usually resolved by comparing the expected offsets into the structure with what actually happens, and understanding what, if anything caused the "gaps".

like image 154
Mats Petersson Avatar answered Jan 01 '23 21:01

Mats Petersson