I am writing a program on a hotel reservation system and have declared a struct Room as follows:
struct Room {
bool isavailable;
bool ispaid;
string customer;
string date;
};
I use a variable read from an input file to create an array of n structs which is all the rooms in the hotel.
struct Room* rooms = new Room[numOfRooms];
I then create the shared memory space and attach it, but when I try to access it after, it doesn't seem to work.
//creates shared memory space
if((shmid = shmget(shmkey, 1000, IPC_CREAT | 0666)) < 0) {
perror("Failed to allocate shared mem");
exit(1);
}
//attaches shared memory to process
Room* shared_memory;
shared_memory = (Room* ) shmat(shmid, NULL, 0);
if(!shared_memory) {
perror("Error attaching");
exit(0);
}
struct Room *PTR = rooms; //temp pointer to rooms array
cout << "test: " << rooms[1].customer << endl; //print before storing in shared memory
rooms = (struct Room*) shared_memory+sizeof(int); //places rooms array in shared memory
delete [] PTR; //deletes the memory location where rooms was stored before being in shared memory
cout << "test: " << rooms[1].customer << endl; //print after storing in shared mem
As you can see I have a cout statement before moving rooms into shared memory which prints the correct thing, but the after cout is empty. Any help would be greatly appreciated, thanks.
std::stringobjects allocate their memory dynamically of the heap. The string data itself will not be in the shared memory, only the pointers to the memory. Using dynamic structures and data of any kind is non-trivial with shared memory (and IPC in general).roomsarray into shared memory. Moreover, in C++, there is no way how to move objects in memory (you can copy their byte representations but only for trivially-copyable types, which is not your case because ofstringmember variables). What you can is to move contents of objects, but this requires their construction (in uninitialized memory) by using move constructor and placement-new syntax. Even then, in case of long strings, their characters will remain in the (not-shared) heap. You will only sharestringobjects themselves, not stored strings.char customer[100];. If you use a dynamically allocated char array, then you have the very same problem as withstd::string.