开发者

Structure Padding in C

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 allocated when I declare a variable of 开发者_运维百科the above structure type. example ee;

and also what is structure padding and if there is any risk associated with structure padding?


Try it. It may be different on different systems.

#include <stdio.h>
#include <stddef.h> /* 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.


Under normal 32 bit it should take 12 bytes - the c field will be padded. This is architecture and compiler depended, however.

You can always use a pragma for the compiler to declare the alignment for the structure (and for some compilers, change the default alignment).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜