映射 [] 运算符段错误

map [] operator segfault

本文关键字:错误 段错误 运算符 映射      更新时间:2023-10-16

当您向 stl 映射添加某些内容时,在什么情况下 acess [] 运算符可能导致段错误?

如何验证它。例:有一个类 TimerManager,它维护事件的 id 映射。

map<int, long> _timerIdsMap; 
Struct GUI
{
   TimerManager manager;
}

然后我注册自己,它工作得很好。

当我发出停止计时器的调用时,也就是有时观察到崩溃的时候。

bool TimerManager::stop_timer( int specifiedEvent )
{
    TRACE("TimerManager::stop_timer() Enter");
    bool retVal = true;
    long timerId = _timerIdsMap[specifiedEvent];
(gdb) where
#0  0x00002adb5d9585a0 in std::_Rb_tree<int, std::pair<int const, long>, std::_Select1st<std::pair<int const, long> >, std::less<int>, std::allocator<std::pair<int const, long> > >::_M_begin() () from Utils.so
#1  0x00002adb5d95954c in std::_Rb_tree<int, std::pair<int const, long>, std::_Select1st<std::pair<int const, long> >, std::less<int>, std::allocator<std::pair<int const, long> > >::lower_bound(int const&) () from Utils.so
#2  0x00002adb5d959583 in std::map<int, long, std::less<int>, std::allocator<std::pair<int const, long> > >::lower_bound(int const&) ()
   from Utils.so
#3  0x00002adb5d95d6fa in std::map<int, long, std::less<int>, std::allocator<std::pair<int const, long> > >::operator[](int const&) ()
   from Utils.so
#4  0x00002adb5d95657f in TimerManager::stop_timer(int) () 

我的问题是如何验证map[]是否包含有效成员。

这是我调用stopTimer函数的方式:

const int TIMERID = 5;
void completeTest(GtkWidget* myWidget,GdkEvent  *event,gpointer   data)
{
    cout<<" test is completed"<<endl;
    GUI* _ptrGUI = (GUI *)data;
    if(_ptrGUI!=NULL)
    {       
        cout<<"stop timer"<<endl;
        if(!_ptrGUI->_timerManager.stop_timer(TIMERID))
        {
            cout<<"fatal error, could not stop the timer"<<endl;
        }

这意味着代码中的某处存在未定义的行为。可能的原因有很多,可能包括:

  • TimerManager物体和/或_timerIdsMap已被销毁。
  • 某处内存损坏(例如,缓冲区溢出)。

一个好的起点可能是瓦尔格林德你的代码。

您在这里遇到段错误,因为:

  1. 您正在访问map中不存在的元素 - 在这种情况下最好使用find方法
  2. 您没有捕获该线程的异常 - 最好捕获异常,如果您需要退出才能优雅地执行此操作