Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local Variables Alignment in C code

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?

like image 691
Electrix Avatar asked Nov 10 '22 19:11

Electrix


1 Answers

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.

like image 150
Yu Hao Avatar answered Nov 14 '22 22:11

Yu Hao