Search code examples
c++boostboost-interprocess

Inserting in a boost::interprocess::map


I have a following boost::interprocess::map:

using boost::interprocess;  
std::shared_ptr< map<uint32, managed_shared_memory*> > myMap;

I have a method() which inserts into this map:

void InsertInMap(uint32 i)
{
    myMap->insert( std::make_pair (i,                       // runtime error here
               new managed_shared_memory(create_only, "Test", 256)) );    

}

And in main(), I call it like this:

int main()
{
    InsertInMap(1);
}

This compiles fine.

But when I run my program, I get the following run-time error at the marked line (while insertion):

memory access violation occurred at address ......, while attempting to read inaccessible data

Am I missing something?


Solution

  • You need to do

    myMap = boost::shared_ptr< map<uint32, managed_shared_memory*> > (new map<uint32, managed_shared_memory*> );

    to allocate the memory for the shared pointer before you use it to add to the map. You are getting this error because myMap is conceptually the same as a null pointer until you allocate memory for it.