C++ - 获取特定内存地址的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12298208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:08:22  来源:igfitidea点击:

C++ - Get value of a particular memory address

c++pointersmemorydereferencememory-address

提问by Zyyk Savvins

I was wondering whether it is possible to do something like this:

我想知道是否有可能做这样的事情:

unsigned int address = 0x0001FBDC; // Random address :P
int value = *address; // Dereference of address

Meaning, is it possible to get the value of a particular address in memory ?

意思是,是否有可能获得内存中特定地址的值?

Thanks

谢谢

回答by Kerrek SB

You can and should write it like this:

你可以而且应该这样写:

#include <cstdint>

uintptr_t p = 0x0001FBDC;
int value = *reinterpret_cast<int *>(p);

Note that unless there is some guarantee that ppoints to an integer, this is undefined behaviour. A standard operating system will kill your process if you try to access an address that it didn't expect you to address. However, this may be a common pattern in free-standing programs.

请注意,除非有一些保证p指向整数,否则这是未定义的行为。如果您尝试访问它不希望您访问的地址,标准操作系统将终止您的进程。但是,这可能是独立程序中的常见模式。

(Earlier versions of C++ should say #include <stdint.h>and intptr_t.)

(早期版本的 C++ 应该说#include <stdint.h>intptr_t。)