Reputation: 3088
I have two programs,
Program A is like this,
int main(int argc, char** argv) {
char* s = "hello";
printf(s);
return (EXIT_SUCCESS);
}
The base address of s is 0x80484e0 "hello", Now I have Program B, as below
int main(int argc, char** argv) {
void* p = (void*)0x80484e0;
char* c = (char*)p;
while(*c)
{
printf("%c",*c);
c++;
}
return (EXIT_SUCCESS);
}
In program B 'p' is pointing to the same base address as 's' in Program B but the contents are not same.
Even though 'p' and 's' are having same base address their contents are not same, is it because they are running as different programs in different address space?
Upvotes: 0
Views: 888
Reputation: 161
I believe that this will never work.
In program A, "hello" is a string that comes with the executable, and loads into memory when you call that program.
Upvotes: 0
Reputation: 34912
If you're using pretty much any operating system, there'll be the concept of virtual memory. So a certain memory address in one process is not necessarily the same in the other process. Even if it did map to the same physical address by some sheer chance, then by trying to read it you would, hopefully, get a segmentation fault because you're accessing memory that the process doesn't "own".
Upvotes: 2
Reputation: 182684
In program B 'p' is pointing to the same base address as 's' in Program B but the contents are not same.
That's the magic of virtual addresses and separate address spaces. You need to look into "shared memory" for your platform.
Addresses used by a program are virtual. They're not the same as the physical address in RAM. The kernel does some nice (nasty) stuff with the help of the MMU and a page table and hides this from the process.
So for example on a 32b system a process thinks it's the sole user of the memory - it can use addresses from 0
to 0xffffffff
- with certain restrictions.
If you happen to be on a POSIX system, you can look into mmap
and shm_open
.
Upvotes: 4