I have edited 1.c as below.
#include<stdio.h>
int x=100;
int main(void)
{
printf("%p",&x);
while(1);
return 0;
}
Then I opened Command Prompt and run this program and got Output 00402000 while program still running. Now I run 2.c
#include<stdio.h>
int main(void)
{
int *p=(int *)0x00402000;
printf("%d",*p);
return 0;
}
in another instance of command prompt and got output -1, I expect 100 which is in location 00402000. please explain why is this behavior?
First and foremost, let me say that in modern operating systems, the address values that your program sees (like that 0x00402000) are not physical addresses. They are virtual addresses, they're private to the owning process (i. e. make no sense or mean something else in other processes), and are mapped to physical addresses via a CPU-based mechanism ("the paging unit") that only OS has control over.
If you want to share a variable between different processes, there's a mechanism called shared memory. Read up on it. The relevant APIs are CreateFileMapping
with the the first parameter being INVALID_HANDLE_VALUE
, MapViewOfFile
, OpenFileMapping
. There are other ways of interprocess communication, too.
If you want to read process' memory without that process' explicit cooperation, you need to read up on debugging API. This is a much trickier job than using shared memory.
What you've coded, by the way, is a classic undefined behavior.
To demo the address space concept, modify your second example to:
#include<stdio.h>
int y = 101;
int main(void)
{
int *p=(int *)0x00402000; // hope this works??
printf("%d",*p);
printf("%p", p); // print value of p to ensure correct assignment
return 0;
}
It probably/might print "101" !! This is because the OS treats each address space the same. So the, global var for an int
regardless of its name probably gets allocated to location 0x004002000.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With