Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is a struct stored in memory?

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;
    }
};
like image 613
Josh C Avatar asked Nov 25 '13 16:11

Josh C


2 Answers

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.

like image 116
Mike Seymour Avatar answered Oct 23 '22 22:10

Mike Seymour


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.

like image 26
Luchian Grigore Avatar answered Oct 23 '22 21:10

Luchian Grigore