I'm trying to understand how packing of a struct variable affects the way local variables on the stack are assigned 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 struct variables and 1 integer. The GCC compiler has decided to assign addresses like this:
&i 0x00007FFFFFFFDF0C
&myStruct1 0x00007FFFFFFFDF10
&myStruct2 0x00007FFFFFFFDF20
There is no padding within the struct - the size of the struct is 6 bytes.
Question is why is myStruct2 on a 2-byte boundary when it could have been placed on the next 6 bytes after myStruct1?
In your code, myStruct1
and myStruct2
are two local variables, their address don't need to be next to each other. It's perfectly legal for GCC to put them like that.
Compare it with this:
struct s myStruct[2];
myStruct[0]
and myStrcut[1]
must be next to each other because they are in the same array.
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