Difference between memory addresses of variables is constant

烂漫一生 提交于 2019-12-12 04:55:55

问题


I ran the following code and this is the output I got:

#include <stdio.h>

int main()
{
    int x = 3;
    int y = x;
    printf("%d\n", &x);
    printf("%d\n", &y);
    getchar();
    return 0;
}

Output:

3078020
3078008

Now, the output changes every time I run the program, but the difference between the location of x to the location of y is always 12. I wondered why.

Edit: I understand why the difference is constant. What I don't understand is why the difference is specifically 12, and why the memory address of y, who's defined later, is less than x's.


回答1:


The addresses themselves may well change due to protective measures such as address space layout randomisation (ASLR).

This is something done to mitigate the possibility of an attack vector on code. If it always loads at the same address, it's more likely that a successful attack can be made.

By moving the addresses around each time it loads, it becomes much more difficult for an attack to work everywhere (or anywhere, really).

However, the fact that both variables will be on the stack in a single stack frame (assuming the implementation even uses a stack which is by no means guaranteed), the difference between them will be very unlikely to change.




回答2:


In your code,

printf("%d\n", &x);

is not the correct way to print a pointer value. What you need is

printf("%p\n", (void *)&x);

That said, the difference between the addresses is constant because those two variables are usually placed in successive memory locations in stack. However, AFAIK this is not guranteed in c standard. Only thing guraneted is sizeof(a) [size of a datatype] will be fixed for a particular platform.




回答3:


To print the address of a variable you have to use the %p not %d.

To print the integer value only you have to give %d.

printf("%d\n",x);// It will print the value of x
printf("%p\n",(void*)&x);// It will print the address of x.

From the man page of printf

p      The void * pointer argument is printed in hexadecimal


来源:https://stackoverflow.com/questions/29408669/difference-between-memory-addresses-of-variables-is-constant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!