【发布时间】: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 << &ptr;与cout << (void*)ptr;进行比较。所有变量都有地址(它们存储的地址),但指针变量还有指向的地址。这是很多混乱的根源。 -
&short_string 和你想象的不一样
标签: c++ windows memory ollydbg