I have a C# background. I am very much a newbie to a low-level language like C.
In C#, struct's memory is laid out by the compiler by default. The compiler can re-order data fields or pad additional bits between fields implicitly. So, I had to specify some special attribute to override this behavior for exact layout.
AFAIK, C does not reorder or align memory layout of a struct by default. However, I heard there's a little exception that is very hard to find.
What is C's memory layout behavior? What should be re-ordered/aligned and not?
It's implementation-specific, but in practice the rule (in the absence of #pragma pack or the like) is:
sizeof(T) bytes.So, given the following struct:
struct ST {    char ch1;    short s;    char ch2;    long long ll;    int i; };   ch1 is at offset 0s at offset 2ch2 is at offset 4, immediately after sll at offset 8i is at offset 16, right after llSo sizeof(ST) is 24.
It can be reduced to 16 bytes by rearranging the members to avoid padding:
struct ST {    long long ll; // @ 0    int i;        // @ 8    short s;      // @ 12    char ch1;     // @ 14    char ch2;     // @ 15 } ST; 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With