使用find函数时,在std :: map中获取SIGSEGV

时间:2017-03-23 19:21:10

标签: c++ gdb stdmap sigsegv

我正在运行一些小型在线游戏,但有时会出现服务器崩溃。我无法找到导致SIGSEGV的原因。 gdb带给我这个功能:

bool Player::getStorageValue(const uint32_t key, int32_t& value) const
{
    auto it = storageMap.find(key);
    if (it == storageMap.end()) {
        value = -1;
        return false;
}

    value = it->second;
    return true;
}

我能以某种方式更好地保护它,不让程序试图访问受限制的内存区域吗?

继续我的gdb日志:

(gdb) bt full
#0  0x000000000054503c in std::less<unsigned int>::operator()(unsigned int const&, unsigned int const&) const ()
No symbol table info available.
#1  0x0000000000740dca in std::_Rb_tree<unsigned int, std::pair<unsigned int const, int>, std::_Select1st<std::pair<unsigned int const, int> >, std::less<unsigned int>, std::allocator<std::pair<unsigned int const, int> > >::_M_lower_bound(std::_Rb_tree_node<std::pair<unsigned int const, int> > const*, std::_Rb_tree_node<std::pair<unsigned int const, int> > const*, unsigned int const&) const ()
No symbol table info available.
#2  0x000000000073e145 in std::_Rb_tree<unsigned int, std::pair<unsigned int const, int>, std::_Select1st<std::pair<unsigned int const, int> >, std::less<unsigned int>, std::allocator<std::pair<unsigned int const, int> > >::find(unsigned int const&) const ()
No symbol table info available.
#3  0x000000000073c46f in std::map<unsigned int, int, std::less<unsigned int>, std::allocator<std::pair<unsigned int const, int> > >::find(unsigned int const&) const ()
No symbol table info available.
#4  0x000000000072dfa2 in Player::getStorageValue(unsigned int, int&) const ()
No symbol table info available.
#5  0x00000000006b2890 in LuaScriptInterface::luaPlayerGetStorageValue(lua_State*) ()

我已将互斥锁添加到代码中,不允许线程同时尝试某些元素

bool Player::getStorageValue(const uint32_t key, int32_t& value) const
{
    std::lock_guard<std::mutex> lockClass(mutex_gp13);

    auto it = storageMap.find(key);
    if (it == storageMap.end()) {
        value = -1;
        return false;
    }

    value = it->second;
    return true;
}

我虽然这应该可以解决我的问题,但今天与gdb日志有相同的SIGSEGV。

编辑: 我发现我没有将互斥量放在写入地图的函数上。我现在要试试这个。

1 个答案:

答案 0 :(得分:2)

鉴于这是一台服务器我认为你可能是多线程的。如果是这种情况,可能是在设置返回值导致迭代器变为无效之前,您的地图正在某处被更改。然后你访问无效的迭代器,程序死得很厉害。

如果是这种情况,那么您需要使用信号量等保护它免受更改。如果没有,那么我们可能需要更多信息,因为代码看起来不错。

相关问题