Struct varies in memory size?

前端 未结 2 1882
独厮守ぢ
独厮守ぢ 2020-12-02 00:42

Why is not 12 in the first case? Tested on: latest versions of gcc and clang, 64bit Linux

struct desc
{
    int** parts;
    int nr;
};

相关标签:
2条回答
  • 2020-12-02 01:18

    The compiler is allowed to add padding between struct members to make processing more efficient. This padding varies by platform, compiler version etc. It's one of the things that make sending structs over the network impossible.

    You can use offsetof to find out where exactly your compiler is adding paddings.

    0 讨论(0)
  • 2020-12-02 01:39

    As the previous answer indicated, the compiler is allowed to add padding. This is usually done because sometimes the hardware requires that certain data types must occur on certain memory boundaries. It looks like your system wants to put pointers on an 8-byte boundary.

    The padding is at the end of the structure and is necessary so that each element in an array of struct desc will still be on an 8-byte boundary.

    0 讨论(0)
提交回复
热议问题