Extra bytes when declaring a member of a struct as uint32_t

半城伤御伤魂 提交于 2019-12-02 01:58:08
Matt Ball

Structs are padded to be an integer multiple of 4 bytes1 so that they are word-aligned. http://en.wikipedia.org/wiki/Data_structure_alignment#Data_structure_padding

See also:


1 As @Mooing Duck commented, this isn't always true:

It's not always a multiple of 4 bytes, it varies (slightly) depending on the members. On the other hand, 99% of the time it's a multiple of 4 bytes.

It's because of alignment. On your platform uint32_t needs to be 4 byte aligned. In order to achieve that dest_addr_64_h has to have two bytes of padding right in front of it because the position right after the two uint8_t members is a multiple of 2 but not 4.

You can use the macro offsetof() to figure out exactly where members are placed within a struct, to see that this is true.

You can either try to make the compiler pack the members tighter together, or you can rearrange the members so that padding isn't needed.

Data types have different alignment requirements based on platform. The extra bytes are used to align one of the members of your structure to a particular size and/or position. IF you need more precise control, you can specify this alignment with __attribute__ or #pragma pack

You need to declare to the compiler to pack the structure

I believe that this will work for GCC

struct test
    {
            unsigned char  field1;
            unsigned short field2;
            unsigned long  field3;
    } __attribute__((__packed__));

In MS it would be something using the pragma packed

http://www.cplusplus.com/forum/general/14659/

#pragma pack(push, 1) // exact fit - no padding
struct MyStruct
{
  char b; 
  int a; 
  int array[2];
};
#pragma pack(pop) //back to whatever the previous packing mode was 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!