Laying structure in C

If I have a structure definition in C of the following

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

      

What memory should be allocated when declaring a variable of the specified structure type. example ee;

and also what is structure deposition and is there a risk associated with structure filling?

+1


source to share


2 answers


Try it. This may vary from system to system.

#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 there are four bytes sizeof(char) == 1

before the field ii

. An additional three bytes are padded. There is a shim to make sure the data types are aligned at the correct bounds for your processor.

If the processor makes unbound access, various things can happen:

  • Access is slower (most x86)
  • Access must be handled by the kernel and slow slow (various PowerPCs) (this caused some PC games to run very fast on fast PPC 603 processors when they ran fine on slower PPC 601 processors.)
  • Program crash (various SPARCs)

I know of no known risks with the supplement. The only problem that actually happens is that two programs compiled with different compilers (usually GCC and MSVC) use different add-ons and cannot share structures. It can also lead to crashes if code from different compilers is linked together. Since padding is often specified by the ABI framework, this is rarely seen.

+10


source


A normal 32-bit field should be 12 bytes - the field c

will be padded. However, this is architecture and compiler dependent.



You can always use the pragma

compiler to declare the alignment for the structure (and for some compilers, change the default alignment).

0


source







All Articles