Memory alignment (especially with C)

If you have a structure inside the structure, say:

struct { double a; struct { char *b[20]; char c; }d; }e; 

will need to start with a multiple of struct d or a multiple of the largest member of d (char * b [20])?

+4
source share
2 answers

It depends on the compiler and settings. In most cases, it starts with the first drill down, which in your case is sizeof(char*) . Note that this is not sizeof(char*) * 20 , as it is an array, not a native type. Also note that in your case, struct e will always start at least with sizeof(double) drill down, and so struct d will work too.

+4
source

Structure e will begin with any alignment necessary so that members and the structure as a whole are accessible.

This alignment will be different for different implementations.

We know that alignment for e will be at least as strict as alignmentf for double , and at least as strict as alignment for ed , and ed alignment will be no less as strict as alignment for it members.

Unlike other answers, scalar type alignment does not necessarily match its size. For example, it is possible that double can be 8 bytes, but only 4-byte alignment is required. Aligning each scalar type (integer, floating point, pointer) to its full size is quite common, but it is not universal.

And note that optimal alignment may be more stringent than the required alignment. On x86, as I understand it, the processor can access objects on any byte boundary, but access to correctly aligned objects is more efficient. (On other CPUs, inconsistent access may require software support.) Compilers typically align objects for maximum efficiency (but may provide custom extensions to save space).

But alignment for a type cannot exceed its size. For example, you cannot have a 3-byte type that requires 4-byte alignment. Arrays cannot have gaps between their elements. (In this case, the compiler would probably apply the type to 4 bytes, and the padding would be part of the object, not inserted between objects.)

+5
source

All Articles