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.