'sizeof' keyword returns wrong size

The C/C++ ‘sizeof’ keyword in a PX4 code for the structure below returns wrong 48 instead of correct 46.

Is it a bug?

struct Frame {
    uint8_t sync;
    uint8_t groups;
    uint16_t fields;
    float temp; // [deg C]
    float mag[3]; // [Gauss]
    float accel[3]; // [m/s^2]
    float gyro[3]; // [rad/s]
    uint16_t crc;
};

Check this: https://www.geeksforgeeks.org/is-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member/

1 Like

That’s very nice and important info!

According to the link above, the returned value of ‘sizeof’ can be varied by the sequence of arranging the elements of the structure data and even it may change by the kind of the C/C++ compiler.

Since it is true, it is wrong to copy directly a binary structured data from communication to a structured data variable which is normally ‘aligned’.

To resolve this problem, ‘#pragma pack’ directive (preprocessing command) should be used as following in order to make the structure without any padding (blank space):

#pragma pack(push, 1)
struct Frame {
    uint8_t sync;
    uint8_t groups;
    uint16_t fields;
    float temp; // [deg C]
    float mag[3]; // [Gauss]
    float accel[3]; // [m/s^2]
    float gyro[3]; // [rad/s]
    uint16_t crc;
};
#pragma pack(pop)

The first #pragma directive saves the current compiler setting for aligning (arranging) the members of structures (, unions and classes) in some stack memory temporarily and then set the alignment byte unit to ‘1’ to arrange the members without any blank space. The second #pragma directive restores the saved setting.

Reference: #pragma

Thanks for your info. Yes, if you need it to be packed and not aligned, e.g. for serialization than pragma pack makes sense. Otherwise, aligning done by the compiler makes sense for optimization.