gpt4 book ai didi

c++ - map [] 运算符段错误

转载 作者:行者123 更新时间:2023-11-28 06:29:17 25 4
gpt4 key购买 nike

在STL map中添加东西时,acess[]运算符在什么情况下可能会导致segfault??

如何验证它。例子:有一个 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;
}

最佳答案

这意味着有 undefined behaviour在你的代码中的某个地方。可能的原因有很多,可能包括:

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

一个好的起点可能是 Valgrind你的代码。

关于c++ - map [] 运算符段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27901122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com