Search code examples
c++stldumpaccess-violationunordered-map

Can a find() on an empty unordered_map lead to an access violation?


I'm investigating a dump, caused by an access violation.
On that particular line of code, there is the following line:

if (internal_map.find(uiElemKey) == internal_map.end() || 
    internal_map[uiElemKey].find(m_iPID) == internal_map[uiElemKey].end() || 
    internal_map[uiElemKey][m_iPID].find(idx) == internal_map[uiElemKey][m_iPID].end()) {

In the watch-window I can see that the amount of entries in internal_map equals 0.

In my opinion, the access violation might be caused by following reasons:

  1. As there are no entries in the map, the find() method generates an exception.
  2. As the are no entries in the map, the end() method generates an exception.
  3. The find() method and the end() method are working fine, but give different results, which leads to the following condition, where an access violation happens.

I think that the access violation can be avoided, using this condition:

if (internal_map.size() == 0                                              ||
    internal_map.find(uiElemKey) == internal_map.end()                    || 
    internal_map[uiElemKey].find(m_iPID) == internal_map[uiElemKey].end() || 
    internal_map[uiElemKey][m_iPID].find(idx) == internal_map[uiElemKey][m_iPID].end()) {

Can somebody confirm this is correct and explain which reason is the correct one?
Thanks in advance

P.s. for your information: I'm doing dump analysis, and it's almost impossible to reproduce the mentioned problem, so just trying and see what happens is not an option.


Solution

  • Assuming that the unordered map is not being modified by some other thread when find() is executing, there is no chance that find() or end() will throw an exception or crash. Their behavior is defined for empty container. So there is no way to corrupt the map by just calling them. Saying this, your test for size() is redundant.