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

Why &x prints a different value every time I run this program?

本文关键字:打印 运行 程序 为什么      更新时间:2023-10-16
#include <iostream>
using namespace std;
int main() {
    cout << "Hello, World!" << endl;
    int x = 10;
    printf("%dn",&x);
    printf("%d",x);
    return 0;
}

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

存储器中存储的位置存储了从执行到执行的更改。您应该使用%p(通常用于指针(,而是使用%d(用于整数(显示x的地址,但是这不会改变这样一个事实,即每次启动程序时地址都会有所不同。

如果我没记错的话,随机化是通过地址空间布局随机化完成的,以防止某些类型的利用。

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

#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("%pn",location_of_x);
    printf("%dn",x);
    // And this is how you indirect through location_of_x
    printf("%dn",*location_of_x); //
    return 0;
}
相关文章: