I am trying to share an unordered map(hash map) but it is ending up with the Floating point exception at the line where it tries to insert the data in the map.
Could someone please help in understanding where I am going wrong?
#include <iostream>
#include <string>
#include <unordered_map>
#include <sys/ipc.h>
#include <sys/shm.h>
int main ()
{
std::unordered_map<std::string,double> *tmp;
key_t key = 5678;
int shmid = shmget(key, 1000, IPC_CREAT | IPC_EXCL | 644);
if(shmid == -1){
std::cerr << "Failed to create the shared segment." << std::endl;
exit(-1);
}
void *addr = shmat(shmid, NULL, 0);
if(addr == (void*)-1){
std::cerr << "Failed to attach the segment to the process." << std::endl;
exit(-1);
}
tmp = static_cast< std::unordered_map<std::string,double>* >(addr);
tmp->insert (std::pair<std::string,double>("abc",1.2));
shmdt(addr);
return 0;
}
Thanks.
You are casting your shared memory address to a pointer to a map, but you never call the constructor to actually create a map at that address. This is likely not going to work the way you want, anyway, since the map may allocate and deallocate memory for it's own use that will come from the heap, not from your shared memory area.
In general, you can't share complex structures between processes. In particular, pointers to objects in the virtual address space of one process won't be valid in another, and most container implementations will involve pointers.
You could look at the Boost.Interprocess library which contains various containers and allocators suitable for sharing; in particular, their version of
unordered_map
can be placed in shared memory, as long as you use their shared memory allocator, so you might simply be able to use that as a replacement forstd::unordered_map
(although you'd still need a replacement forstd::string
as the key).