Daneill
Daneill

Reputation: 23

variable arrangement in vs2010

Code://VS2010

int a;
int b;
int c;
int d;

int main(){
    //output the address of global variables
    printf("0x%x, 0x%x, 0x%x, 0x%x\n", &a, &b, &c, &d);

    int a1, b1, c1, d1;
    //output the address of local variables
    printf("0x%x, 0x%x, 0x%x, 0x%x\n", &a1, &b1, &c1, &d1);

    int a2 = 1;
    int b2 = 2; int c2; int d2 = 4;
    //output the address of local variables
    printf("0x%x, 0x%x, 0x%x, 0x%x\n", &a2, &b2, &c2, &d2);
}

Output:

0x1197a44, 0x1197a3c, 0x1197a40, 0x1197a38
0x15fb00, 0x15faf4, 0x15fae8, 0x15fadc
0x15fad0, 0x15fac4, 0x15fab8, 0x15faac

My Question:

  1. Why are the global variables not stored in order? The above output represents that they are out-of-order.

  2. Why are the local varialbes not stored continuously? The above output represents that VS2010 inserts 8byte space between every two of them.

Does anybody can help me? Thanks very much!

---------------------------------------complement------------------------------------------

Code:\gcc version 4.6.1 (Ubuntu/Linaro 4.6.1-9ubuntu3)

int a;
int b;
int c;
int d;

void main(){
        //output the address of global variables
    printf("%p, %p, %p, %p\n", &a, &b, &c, &d);

    int a1, b1, c1, d1;
        //output the address of local variables
    printf("%p, %p, %p, %p\n", &a1, &b1, &c1, &d1);

    int a2 = 1;
    int b2 = 2; int c2; int d2 = 4;
        //output the address of local variables
    printf("%p, %p, %p, %p\n", &a2, &b2, &c2, &d2);
}

Output:

0x60103c, 0x601034, 0x601038, 0x601030
0x7fff126253a0, 0x7fff126253a4, 0x7fff126253a8, 0x7fff126253ac
0x7fff126253b0, 0x7fff126253b4, 0x7fff126253b8, 0x7fff126253bc

In gcc, the address of global variable and local variable is continuous and in-order.

So I want to know what and why the vs2010 does that for our code.

Upvotes: 2

Views: 188

Answers (2)

Mankarse
Mankarse

Reputation: 40643

Your program has undefined behaviour, because the types specified in the format string do not match the types of the other arguments passed to the printf.

As such, your code does not demonstrate that the variables are not stored continuously.

Upvotes: 0

fefe
fefe

Reputation: 3442

Neither of them is specified by the specification, the compiler can do what it want to do.

As to the local variables, you are probably using the DEBUG build, and the padding is inserted to check stack integrity. If any memory overrun happens, the padding would be overwritten and the overrun would be spotted.

Upvotes: 2

Related Questions