Can heap memory be shared between 2 different processes? In boost interprocess documentation,there is a statement that managed heap memory does not create system wide resources
-
No regular dynamic allocated memory cannot be shared between two processes in general. There are operating systems though which support shared memory, or even allow to access the memory hosted in a different process. – πάντα ῥεῖ Oct 07 '18 at 09:47
-
1Major operating systems like Linux, macOS and Windows all support inter-process shared memory, so I would say that in general it *can* be shared. – G. Sliepen Oct 07 '18 at 10:04
1 Answers
Nothing is foreseen in the C++ standard for shared memory between processes. In fact, each process runs in its own address space and manages its dynamic memory in that address space, so there is no way to share the "heap".
However, operating systems give you some means to share memory between processes. The best known way is the use of memory mapped files, which are supported across a wide range of OS, but in an OS specific way, so non portable. boost proposes a portable implementation which hides the OS specific part.
You may very well use the memory area obtained in this way for your objects. You could use placement new to instantiate objects. You could even create a custom allocator to create dynamic objects in this memory area.
However, this requires extra care, since you have to take into consideration IPC synchronisation to avoid races, and you need to remember that any pointer created by one process is garbage for the other process (since it runs in antoher, independent address space).

- 68,716
- 7
- 72
- 138