Search code examples
c++lambdathreadpoolshared-ptrc++14

Unordered map in shared_ptr SIGSEGV


I'm building server for speech recognizer. I'm using thread pooling to serve clients.

I needed to create unordered map to save instance of recognizer for each client. So I create this_

std::shared_ptr<std::unordered_map<int ,SOnlineSpeechRecognizerI *>> user_recognizers;
std::mutex rec_mutex;

So on client connection I create instance of recognizer and I need to insert data to user_recognizers. My lambda function for that is :

echo.onopen=[user_recognizers, &rec_mutex](auto connection) {
    std::cout << "Server: Opened connection " << (size_t)connection.get() << std::endl;
    SOnlineSpeechRecognizerI *rec = recognizer::initRecognizer();
    if(!rec){
        connection.
    }
    std::pair<int, SOnlineSpeechRecognizerI *> myrec ((size_t)connection.get(), rec);
    rec_mutex.lock();
    (*user_recognizers).insert(myrec); //error here
    rec_mutex.unlock();
};

connection.get() return int ID of the connection.

I'm getting SIGSEGV. Valgrind gives me a little hint:

Access not within mapped region at address 0x8

Solution

  • Apparently you don't initialize user_recognizers, therefore it holds a null pointer leading to segfault when you access it.

    You can initialize it for example like this:

    using MyMap = std::unordered_map<int ,SOnlineSpeechRecognizerI *>;
    std::shared_ptr<MyMap> user_recognizers { std::make_shared<MyMap>() };
    

    (I assume user_recognizers is a some class member so it can't be declared with auto)