putting objects into shared memory regions

Using the shmget and shmat function you can allocate a block of memory that multiple processes can access.  But suppose you want to store an object in that memory.  So you copy the object to the shared memory using memcpy, and then any process can access it with an object* pointer.  

This seems like it would work fine.  But what if the object itself contains an internal pointer to another memory location?

For example, suppose you have:

class Box {
     char* p;

     Box() { p = new char[100]; }
     ~Box() { delete[] p; }
     char* data() { return p; }

And then you do:

Box box;
void* sharedmem = shmat(shmid, (void*) 0, 0);
memcpy (sharedmem, &box, sizeof(box));

Now a copy of the object "box" is in the shared memory region.  So, I set a pointer to it like:
Box* pbox = (Box*) sharedmem;

And then I can access the data in Box by doing:

But wouldn't this cause a segmentation violation if another process tried to access the data in box?  Because even though box itself is stored in the shared memory region, the data pointed to by the member variable of box is NOT in the shared memory region, and is in fact, part of another process.  So wouldn't this be an unsafe thing to do?  If so, is there any possible way to share objects between processes?
Who is Participating?
efnConnect With a Mentor Commented:
You're right, that would not be safe.  However, a self-contained object in shared memory could be shared between processes.  Or an object that was not self-contained could be shared if you were careful.  The memory not contained in the object would have to be in some shared memory area, and you would have to manage it yourself, using offsets from the beginning of the shared memory area.  That is, the usual malloc or new facilities won't manage a shared memory area for you, and its address will not necessarily be the same in all processes that use it, so pointers within it are not portable across processes, and you will have to use offsets from the beginning of the area to identify locations portably.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.