Local permutation of variables in C code

I am trying to understand how wrapping a struct variable affects how local variables are assigned to the stack on an address.

#include <stdio.h> struct s { short s1; short s2; short s3; }; int main() { struct s myStruct1; struct s myStruct2; myStruct1.s1 = 1; myStruct1.s2 = 2; myStruct1.s3 = 3; myStruct2.s1 = 4; myStruct2.s2 = 5; myStruct2.s3 = 6; int i = 0xFF; printf("Size of struct s: %d", sizeof(myStruct1)); return 0; } 

In my program above, I have 2 structural variables and 1 integer. The GCC compiler decided to assign addresses as follows:

 &i 0x00007FFFFFFFDF0C &myStruct1 0x00007FFFFFFFDF10 &myStruct2 0x00007FFFFFFFDF20 

There are no indents in the structure β€” the size of the structure is 6 bytes.

Question: why is myStruct2 on a 2-byte boundary when it could be placed in the next 6 bytes after myStruct1?

+5
source share
1 answer

There are two local variables in your code myStruct1 and myStruct2 , their address should not be next to each other. It is perfectly legal for the GCC to put them like that.

Compare this to this:

 struct s myStruct[2]; 

myStruct[0] and myStrcut[1] must be next to each other because they are in the same array.

+1
source

Source: https://habr.com/ru/post/1212931/


All Articles