Search code examples
c++windowsmemoryollydbg

How to correctly print address of a variable in memory?


i'm trying to understand how c or c++ structures ar stored in memory.

i wrote a small program in c++ and i compiled and ran it into a debugger. i used printf with %p and &variable to print the address but the address printed out and the actual address in memory are completely different. in fact the printed address is not even valid.

any idea how can i correctly print the real address of a variable or structure?

thanks

here is the source code of the program i wrote:

#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;
}

this is the output from the compiled program: compiled program

this is the location in memory of the variables: debugger output


Solution

  • To print the location of your string, you need to: std::cout << (void*)short_string;

    In your example you write the address of where is your local variable, which is on the stack