【问题标题】:How to correctly print address of a variable in memory?如何正确打印内存中变量的地址?
【发布时间】:2019-07-30 16:52:17
【问题描述】:

我试图了解 c 或 c++ 结构是如何存储在内存中的。

我用 C++ 编写了一个小程序,然后编译并运行到调试器中。我使用 printf 和 %p 和 &variable 来打印地址,但是打印出来的地址和内存中的实际地址完全不同。实际上打印的地址甚至是无效的。

知道如何正确打印变量或结构的真实地址吗?

谢谢

这是我写的程序的源代码:

#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <conio.h>

#define XXX __asm__("nop");

int main(){
    XXX;
    XXX;
    const char *short_string = "this is a short string";
    const wchar_t *long_string = L"this is a long string";
    int a = 2;
    int b = 3;
    int c = a + b;
    int *pointer_to_a = &a;

    std::cout << "the address of short_string is: " << &short_string << std::endl;
    std::cout << "the address of long_string is: " << &long_string << std::endl;
    std::cout << "the address of a is: " << &a << std::endl;
    std::cout << "the address of a is: " << pointer_to_a << std::endl;
    std::cout << a << "+" << b << "=" << c << std::endl;
    std::cout << std::endl;
    XXX;
    XXX;
    getch();
    return 0;
}

这是编译程序的输出:

这是变量在内存中的位置:

【问题讨论】:

  • 您似乎犯了常见的新手错误,将指针变量的地址与变量指向的地址混淆了。尝试将cout &lt;&lt; &amp;ptr;cout &lt;&lt; (void*)ptr; 进行比较。所有变量都有地址(它们存储的地址),但指针变量还有指向的地址。这是很多混乱的根源。
  • &short_string 和你想象的不一样

标签: c++ windows memory ollydbg


【解决方案1】:

要打印字符串的位置,您需要: std::cout

在你的例子中,你写了你的局部变量的地址,它在堆栈上

【讨论】:

    猜你喜欢
    • 2023-02-07
    • 2016-10-10
    • 1970-01-01
    • 2013-04-30
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 2014-07-26
    • 1970-01-01
    相关资源
    最近更新 更多