Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::unordered_map vector subscript out of range

I'm using std::unordered_map<void *, size_t> to hold some values and I'm getting "vector subscript out of range" when adding a new value. I'm using Visual Studio 2012 and the error trace is:

std::vector<std::_List_unchecked_iterator<std::_List_val<std::_List_simple_types<std::pair<void * const,unsigned int> > > >,std::_Wrap_alloc<std::allocator<std::_List_unchecked_iterator<std::_List_val<std::_List_simple_types<std::pair<void * const,unsigned int> > > > > > >::operator[](unsigned int _Pos) Line 1140  C++
std::_Hash<std::_Umap_traits<void *,unsigned int,std::_Uhash_compare<void *,std::hash<void *>,std::equal_to<void *> >,std::allocator<std::pair<void * const,unsigned int> >,0> >::_Vec_lo(unsigned int _Bucket) Line 907    C++
std::_Hash<std::_Umap_traits<void *,unsigned int,std::_Uhash_compare<void *,std::hash<void *>,std::equal_to<void *> >,std::allocator<std::pair<void * const,unsigned int> >,0> >::_End(unsigned int _Bucket) Line 936   C++
std::_Hash<std::_Umap_traits<void *,unsigned int,std::_Uhash_compare<void *,std::hash<void *>,std::equal_to<void *> >,std::allocator<std::pair<void * const,unsigned int> >,0> >::_Insert<std::pair<void * const,unsigned int>,std::_Nil>(std::pair<void * const,unsigned int> && _Val, std::_Nil _Pnode) Line 872  C++
std::_Hash<std::_Umap_traits<void *,unsigned int,std::_Uhash_compare<void *,std::hash<void *>,std::equal_to<void *> >,std::allocator<std::pair<void * const,unsigned int> >,0> >::insert(std::pair<void * const,unsigned int> && _Val) Line 371 C++

specificaly:

_Unchecked_iterator& _Vec_lo(size_type _Bucket)
{   // return reference to begin() for _Bucket
return (_Vec[2 * _Bucket]);
}

where _Vec is an empty vector and _Bucket is the pointer hash (> 0). The same thing happenes when the key type isn't void *, but uintptr_t. Is it a VS bug or am I doing something wrong?

Note: this question is related to c++ unorderedmap vector subscript out of range - this is the same problem, but the answer isn't related

like image 799
krojew Avatar asked Apr 11 '13 19:04

krojew


1 Answers

It's a pretty old question and I don't know if my answer suits the question. But since we didn't get additional information from the OP and I ran into the same runtime error, I'm posting my solution to my specific problem. Maybe someone finds it useful aswell.

In my case it was a static initialization order problem. I accessed the unordered_map (which was a static class member) before the static members of that class were initialized.

That resulted in undefined behavior (accessing objects that are not initialized) which crashed the application with that runtime error.

How to solve static initialization order problems can be found here.

like image 141
Timo Avatar answered Oct 24 '22 18:10

Timo