簡體   English   中英

map []運算符segfault

[英]map [] operator segfault

在stl映射中添加內容時,在什么情況下acess []運算符可能導致段錯誤?

如何驗證。 示例:有一個TimerManager類,用於維護ID與事件的映射。

map<int, long> _timerIdsMap; 

Struct GUI
{
   TimerManager manager;
}

然后,我注冊自己,它運行正常。

當我發出停止計時器的呼叫時(即when),有時會觀察到崩潰。

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已被破壞。
  • 某處存在內存損壞(例如,緩沖區溢出)。
  • 等等

一個好的起點可能是Valgrind您的代碼。

您在這里遇到段錯誤,原因是:

  1. 您正在訪問地圖中不存在的元素-在這種情況下最好使用find方法
  2. 您沒有捕獲該線程的異常-更好地捕獲異常,以及是否需要退出以正常執行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM