Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory alignment (Using C specifically)

Tags:

c

memory

struct

If you've got a struct within a struct, say:

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

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

like image 384
Max Avatar asked Jan 18 '23 15:01

Max


1 Answers

The struct e will start at whatever alignment is necessary for the members, and the struct as a whole, to be accessible.

That alignment will vary for different implementations.

We know that the alignment for e will be at least as strict as the alignmentf for double and at least as strict as the alignment for e.d -- and the alignment of e.d will be at least as strict as the alignment for its members.

Contrary to the other answers, the alignment of a scalar type is not necessarily the same as its size. For example, it's possible that double might be 8 bytes, but only require 4-byte alignment. Aligning each scalar type (integer, floating-point, pointer) to its full size is fairly common, but it's not universal.

And note that the optimal alignment may be more strict than the required alignment. On the x86, as I understand it, the CPU can access objects on any byte boundary -- but access to properly aligned objects is more efficient. (On other CPUs, misaligned access may require software support.) Compilers will typically align objects for maximum efficiency (but may provide non-standard extensions to save space).

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

like image 164
Keith Thompson Avatar answered Jan 28 '23 20:01

Keith Thompson