为什么& x每次运行此程序时都会打印不同的值?

时间:2018-02-20 07:44:07

标签: c++

#include <iostream>

using namespace std;

int main() {
    cout << "Hello, World!" << endl;
    int x = 10;
    printf("%d\n",&x);
    printf("%d",x);
    return 0;
}

为什么每次运行此程序时&x都会打印出一个新值?在这种情况下,如何从value_of_x打印location_of_x,并将输出值视为10

2 个答案:

答案 0 :(得分:6)

存储本地变量的内存中的位置从执行变为执行。您应该使用%p(通常用于指针)而不是%d(用于整数)来显示x的地址,但是这并不会改变每次启动程序时地址都不同的事实。登记/> 如果我没记错的话,随机化是通过Address space layout randomization完成的,并且是为了防止某些类型的攻击。<​​/ p>

答案 1 :(得分:2)

回答你的问题&#34;如何在这种情况下打印*_location_of_x,并将输出视为10?&#34;请参阅以下内容:

#include <stdio.h>  // If you use printf, you will need this.
                    // (You could use <cstdio>, but I wouldn't bother.)

int main() {
    printf("Hello, World!\n");     // Mixing iostream and stdio output is a bit of
                                   // a code smell.
    int x = 10;
    int *location_of_x = &x;       // No leading _.  Much easier to avoid
                                   // reserved names that way.
    // Use %p to print pointers.  Note that the value printed here is likely to
    // vary from run to run - this makes buffer overflow harder (but not
    // impossible) to exploit
    printf("%p\n",location_of_x);
    printf("%d\n",x);
    // And this is how you indirect through location_of_x
    printf("%d\n",*location_of_x); //
    return 0;
}