简体   繁体   中英

Get the value of a variable using the hexadecimal memory address

I just want to get the value using the hex address:

#include<stdio.h>

int main()
{
   int *hold, value=10;
   hold = &value;
   printf("%p",hold);
}

It gives me the address 0x7fffd7c24334 . I just want to know that if there is a way in C or C++ so that I can get directly the value of "value" using hex number 0x7fffd7c24334 for the time being. I suppose the address of the variable hold is the same for sometime so that 0x7fffd7c24334 still point to value , but I am not sure.

Assuming that this address is consistent upon every execution of your program, you can use this:

int value2 = *(int*)0x7fffd7c24334;

But please note that this assumption is generally wrong!

The address of a local variable in a function depends on the state of the stack (the value of the SP register) at the point in execution when the function is called.

It might possibly work in main , since this function is called only once, and the SP register should have the same value upon every execution of your program. But even if it does work, that address will change as soon as you add variables before value . To put it in simple words, don't use this method.

printf("%d",*hold);

De-reference and use %d .

You cannot rely on the hex address.

See here: http://ideone.com/RdY4Ni

我认为你可以使用这个:

printf("%x", hold);

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