在 C++ 中获取地址的内容

发布于 2024-12-11 23:57:40 字数 435 浏览 0 评论 0原文

如果我没有指向内存中地址的指针,但我确实将地址本身作为 uint_32 ,那么在 C++ 中是否可以获取内存中地址的内容?

谢谢

编辑

我正在写入这些位置,并试图查看我的 write() 函数是否正常工作,所以我想手动从地址进行读取。上面提到的“内容”的类型是uint64_t,这就是我尝试做的,但这给了我一个Segmentation Failure

uint64_t *contents = reinterpret_cast<uint64_t*>(start_address);
cout<< hex << "Contents: " << *contents << endl;

我在这里做错了什么?

Is it possible in C++ to get the contents of an address in memory if I don't have a pointer to it, but I do have the address itself as a uint_32?

Thanks

EDIT

I am writing to those locations, and was trying to see if my write() function was working properly, so I wanted to manually do a read from the addresses. The 'contents' mentioned above are of type uint64_t and this is what I've tried doing, but this gives me a Segmentation Fault.

uint64_t *contents = reinterpret_cast<uint64_t*>(start_address);
cout<< hex << "Contents: " << *contents << endl;

What am I doing wrong here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

碍人泪离人颜 2024-12-18 23:57:40

不确定可移植性,但您可以使用reinterpret_cast。例如

uint_32 adrs;
int *p = reinterpret_cast<int*>(adrs);  // int* should be 32-bit for portable code

Unsure of portability, but you can use reinterpret_cast<>. e.g.

uint_32 adrs;
int *p = reinterpret_cast<int*>(adrs);  // int* should be 32-bit for portable code
策马西风 2024-12-18 23:57:40

是的,但前提是该地址位于您的地址空间中(或者如果您在微控制器上运行)或在内核空间中)。否则会导致段错误。

只需将 uint_32 转换为 int 指针,然后取消引用它:

int contents = *((int*)uintAddress);

Yes, but only if the address is in your address space (or if you are running on a microcontroller or in kernel space). Otherwise it will cause a seg fault.

Simply cast the uint_32 to an int pointer, and dereference it:

int contents = *((int*)uintAddress);
花间憩 2024-12-18 23:57:40

是的,您可以,如果您将此整数转换为指针:

SomeData value = *reinterpret_cast<SomeData*>(some_int);

但是您必须 100% 确定您的整数确实是一个地址,否则可能会发生不好的事情。所以这被认为是不好的做法,通常是一种黑客行为。

Yes, you can, if you cast this integer to a pointer:

SomeData value = *reinterpret_cast<SomeData*>(some_int);

But you have to be 100% sure that your integer really is an address, or bad things are likely to happen. So this is considered bad practice and usually a hack.

隱形的亼 2024-12-18 23:57:40

您只需将其转换为指针并取消引用即可。

You just cast it to pointer and dereference.

酒废 2024-12-18 23:57:40

C 风格变体:

uint_32 x = 0xc0de;
int *addr = (int*)x;
printf("Address %d contains %d", x, *addr);

C-style variant:

uint_32 x = 0xc0de;
int *addr = (int*)x;
printf("Address %d contains %d", x, *addr);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文