sizeof() operator in C++Builder gives what appears to be an incorrect structure size

Abstract: sizeof() operator in C++Builder gives what appears to be an incorrect structure size

sizeof() operator in C++Builder gives what appears to be an incorrect structure size

  • Product Name:��C++Builder�
  • Product Version:��All�
  • Product Component:��Standard Libraries�
  • Platform/OS Version:� All

    Description:

    ���� I am using the sizeof() operator in C++Builder to obtain the size of a structure. However, sizeof() gives what appears to be an incorrect size for the structure, one that is larger than expected (i.e. greater than the combined size of its members). Why?

    Answer/Solution:

    ���� The reason for the apparent "incorrect" structure size given by sizeof() is alignment. For C++Builder, the data alignment option is set to Quad Word (see the Advanced Compiler tab of the Project Options) by default. Thus, the observed increase in structure size is due to padding in order to keep Quad Word alignment.


    ���� To get around this and get the more commonly expected result from sizeof(), you can specify Byte alignment for the structure. This can be done in the two following ways...


    ���� // Method 1
    ���� //--------------------
    ���� #pragma option push -a1
    ���� struct {
    ���� // declarations
    ���� } MyStruct;
    ���� #pragma option pop
    ���� //--------------------


    ���� // Method 2
    ���� //--------------------
    ���� #pragma pack(push, 1)
    ���� struct {
    ���� // declarations
    ���� } MyStruct;
    ���� #pragma pack(pop)
    ���� //--------------------


    After doing either of the above, sizeof(MyStruct) will give the structure size as the combined size of its members.

    Author:� Yu-Chen Hsueh