How is a struct stored in memory?

旧巷老猫 提交于 2019-12-12 15:09:22

问题


I have a struct iof_header in my code, and I determined it would be 24 bytes wide. I perform a sizeof(iof_header) and it returns 32 bytes wide.

Question 1 Why is it 32 bytes wide instead of 24?

Question 2 Including its members, how is a struct stored in memory?

Question 3 I find any time I create one of my structs that bytes[4-8 & 20-24] are all NULL, I see this apparent in my char array. The array reads as follows {4 bytes of BASEID_Code, 4 NULL bytes, 8 bytes of zeroed padding, 4 bytes of ASID_Code, 4 NULL bytes, 8 bytes of size} There are NULL bytes at the ends of my unsigned __int32 members, why is this happening?

Is this possibly compile related? Possibly an efficiency thing to make the CPU able to process these data types faster?

struct                      iof_header
{
    union
    {
        struct
        {
            unsigned __int32        BASEID_Code;
            unsigned __int64        padding;
            union
            {
                char                    ASID_Type[4];
                unsigned __int32        ASID_Code;
            };
            unsigned __int64        Size;
        }header;
        char                    header_c[24];
    };
    iof_header()
    {
        header.ASID_Code = 0;
        header.BASEID_Code = 0;
        header.Size = 0;
        header.padding = 0;
    }
};

回答1:


Why is it 32 bytes wide instead of 24?

Probably because padding is added before each __int64 member to meet their alignment requirements.

Including its members, how is a struct stored in memory?

The members are stored in order, with padding inserted where necessary to correctly align each member relative to the start of the structure.

Some compilers have a non-standard extension to "pack" the members, so that padding is not inserted. For example, on GCC you can put __attribute__((packed)) after the structure definition.

Possibly an efficiency thing to make the CPU able to process these data types faster?

Yes. On some processors, unaligned accesses are slow; on others, they aren't allowed at all, and must be emulated by two or more accesses.




回答2:


A compiler is free to add padding bytes after members to preserve alignment requirements. Your __int64 members are probably aligned to 8 bytes, ergo the 4 padding bytes between BASEID_Code and padding.



来源:https://stackoverflow.com/questions/20198002/how-is-a-struct-stored-in-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!