映射 [] 运算符段错误
map [] operator segfault
当您向 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
已被销毁。- 某处内存损坏(例如,缓冲区溢出)。
- 等
一个好的起点可能是瓦尔格林德你的代码。
您在这里遇到段错误,因为:
- 您正在访问map中不存在的元素 - 在这种情况下最好使用find方法
- 您没有捕获该线程的异常 - 最好捕获异常,如果您需要退出才能优雅地执行此操作
相关文章:
- 为什么PyImport_ImportModule python 3.7.2 中出现段错误?
- 为什么在访问 vtkRenderWindow 的"交互器"变量时会发生段错误?
- 全局向量导致 C++ 程序结束时出现段错误
- 为什么重载运算符<<打印特征类成员会导致段错误?
- 更改条件段错误
- 使用 TTF_RenderText() 加载字体时获取段错误 TTF_OpenFontRW()
- 注册对对象工厂的调用会导致段错误
- pthread_create在构造函数段错误中
- Nanoflann发现邻居提出段错误
- C++ 中的构造函数、继承、堆栈、堆、this-pointer 和段错误
- 具有unique_ptr的 CRTP 会导致段错误
- 增强纤维work_stealing屏障会导致段错误
- 当我返回指向结构的指针向量时出现段错误
- C++为什么我的代码没有爆炸/段错误?
- Pthread段错误,使用指向main中变量的指针
- C++ 模板中的段错误
- 相当于Windows/MSVC上的段错误?
- 为什么我的 LLVM JIT 实现出现段错误?
- 为什么访问我的引用捕获变量会导致我的 lambda 函数出现段错误?
- 为什么自删除的全局 Vulkan 实例仅在添加层时才导致段错误?