Writing an unordered card to non-working memory

I am trying to split an unordered map (hash map), but it ends up with a floating point exception in the row where it is trying to insert data into the map.

Did anyone help to understand what I'm 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.

-1
source share
2 answers

In general, you cannot share complex structures between processes. In particular, pointers to objects in the virtual address space of one process will not be valid in another, and most container implementations will contain pointers.

You can look at the Boost.Interprocess library, which contains various containers and dispensers suitable for sharing; in particular, their version of unordered_map can be allocated in shared memory if you use your shared memory allocator, so you can just possibly use this replacement for std::unordered_map (although you still need a replacement for std::string as a key) .

+5
source

You send your shared memory address to a pointer to a map, but you never call the constructor to create a map to this address. In any case, this is unlikely to work the way you want, since the card can allocate and free memory for its own use, which will come from the heap, and not from your shared memory area.

+1
source

All Articles