Reputation: 435
I found an interesting phenomenon when I execute a simple test code:
int main(){
int *p=(int *)0x12f930;
printf("%d",*p);
return 0;
}
Of course it crashed with a segmentation fault. but even I change the 0x12f930
to 0x08048001
(0x08048000+1
, that should be the text area when execute the elf binary), it still crashed with a SF.
then I changed my code as below:
int main()
{
int i=1;
printf("%x",&i);
return 0;
}
the output is 0xf3ee8f0c
, but as I know, the address of user space should be <=0xc0000000
, so I am quite confused.
Anyone can help?
Upvotes: 2
Views: 1350
Reputation: 6674
First, don't ever do it, unless there's a specific need to. But, certain embedded applications and legacy systems, might need the explicit memory access.So, here's and example code:
const unsigned addr = 0xdeadbeee;//This address is an example, which should always be >0xc000000 and const
const unsigned *ptr=(const unsigned*)addr;//Then you can assign it to a pointer after proper casting and keeping it const, unless there's a need to keep it not-const
Be careful, as you may hit an unallocated memory or worse thrash the memory and even cause system instability. Also, the above code is implementation defined and as such not portable among different systems.
If you are executing your program in that OS, you need to understand the memory addressing scheme, followed by OS.Specially, some OS assign random starting address of the stack and/or heap in order to make some difficult to attack memory/processes in the system.So, every time you will execute the program, that processes address will be different.
If you wish to examine a process's memory, you could refer to source of GDB and how they do it.
Upvotes: 2