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
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).
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:
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.