user1281071
user1281071

Reputation: 895

can i use same pointer to call data from different exe file?

I am trying to make two .exe files in c where first one store some data in memory and save data´s pointer to .txt. and second one read pointer from .txt and display them.

first one: fw = fopen("pointer.txt", "w"); fprintf(fw, "%p", &data); fclose(fw);

second one: fr = fopen("pointer.txt", "r"); fscanf(fr, "%p", &pointer);

but when I run the second one it display a random numbers.

what is wrong?

Upvotes: 2

Views: 197

Answers (5)

Alok Save
Alok Save

Reputation: 206656

No You should not do that.
The address may not be valid in the process in which the second exe runs.

Each process is allocated an address space, and each exe runs in separate process. So the address space allotted to the two processes could be completely different.

Usually, a OS will reclaim the memory allotted to an process,However it may not reclaim certain resources like file handles etc. So the memory allotted to the variable will be reclaimed by the OS once the first process ends.

If you want to share contents across two active processes(Both processes are alive when you need to communicate between them), You need a Interprocess Communication Mechanism(IPC), there are various IPC mechanisms and One would usually choose a IPC mechanism depending on performance,Whether processes are related or whether synchronization is required etc.

If you want to share contents across two non-active processes(Either One of the process is not alive when you need to communicate between them), then storing the contents in a file is a good idea but You should store the contents not memory addresses.

Upvotes: 2

torrential coding
torrential coding

Reputation: 1765

You'll need to use IPC mechanisms to achieve that. Have a look at http://en.wikipedia.org/wiki/Shared_memory#In_software

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258698

Processes don't operate on actual memory, but virtual memory allocated to them by the system. So 0x01111 from P1 and 0x01111 from P2 don't point to the same sector of your RAM. Ergo, no, you need to use IPC I guess.

Upvotes: 2

FatalError
FatalError

Reputation: 54641

What you want to do is possible, but your approach is not correct -- each process has its own virtual address space and so an address that's meaningful in one process may not be in another, and either way it will not refer to the same memory.

If you want to share resources between processes like that, you need to ask Windows to let you. See this page for some details: http://msdn.microsoft.com/en-us/library/windows/desktop/aa366878%28v=vs.85%29.aspx.

Upvotes: 1

Luca Martini
Luca Martini

Reputation: 1474

The virtual memory is per-process. See Wikipedia on that.

Upvotes: 1

Related Questions