简体   繁体   中英

How to read a memory address in Visual C++?

In ANSI CI can do this:

const long *address = 0x00000002;  /* Example address */
printf("0x00000002 -> %ld", *address);

And the console will show the content of that memory address. But that code in VC++ throws:

error C2440: 'initializing' : cannot convert from 'int' to 'const long *'

Is there a native way to read memory addresses from VC++ or I have to call the API?

Thanks in advance.

You have the address expressed as an integer. You need to cast it to a pointer of the appropriate type:

const long *address = reinterpret_cast<const long *>(0x00000002);

And you need to perform that cast in standard C++. I'm not sure why you think that the cast can be omitted in standard C++.

Of course, when you run your code, you will encounter a segmentation fault.

To set that address, use a cast like

const long* address = (const long*) 0x0000002;  // C style

or

const long* address = 
   reinterpret_cast<const long*>(0x000002); // C++ style

BTW, on most systems 0x0000002 is not a valid address (in the usual virtual address space of applications). See wikipage on virtual memory & virtual address space .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM