Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to access memory allocated to different process? [duplicate]

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?

like image 310
M Sharath Hegde Avatar asked Aug 20 '13 13:08

M Sharath Hegde


2 Answers

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.

like image 129
Seva Alekseyev Avatar answered Oct 19 '22 00:10

Seva Alekseyev


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.

like image 2
JackCColeman Avatar answered Oct 19 '22 00:10

JackCColeman