Structure Padding in C

后端 未结 2 1614
长发绾君心
长发绾君心 2021-01-23 17:15

If I have a structure definition in C of the following

typedef struct example 
{
  char c;
  int ii;
  int iii;
};

What should be the memory al

2条回答
  •  佛祖请我去吃肉
    2021-01-23 18:01

    Try it. It may be different on different systems.

    #include 
    #include  /* for offsetof */
    struct example { char c; int ii; int iii; };
    int main(int argc, char *argv[])
    {
        printf("offsetof(struct example, c) == %zd\n", offsetof(struct example, c));
        printf("offsetof(struct example, ii) == %zd\n", offsetof(struct example, ii));
        printf("offsetof(struct example, iii) == %zd\n", offsetof(struct example, iii));
        return 0;
    }
    

    Output:

    offsetof(struct example, c) == 0
    offsetof(struct example, ii) == 4
    offsetof(struct example, iii) == 8
    

    Note that sizeof(char) == 1, but there are four bytes before the ii field. The extra three bytes are padding. Padding exists to make sure that data types are lined up on the correct boundaries for your processor.

    If a processor makes an unaligned access, various things can happen:

    • The access is slower (most x86)
    • The access must be handled by the kernel and is INCREDIBLY slow (various PowerPC) (This caused some computer games to run very slow on fast PPC 603 processors when they run just fine on slower PPC 601 processors.)
    • The program crashes (various SPARC)

    I know of no known risks with padding. The only problem that really happens is that two programs compiled with different compilers (GCC vs MSVC has been known to cause this) use different padding and cannot share structures. This can also cause crashes if code from different compilers is linked together. Since padding is often specified by the platform ABI, this is rare.

提交回复
热议问题