Note that there are some explanatory texts on larger screens.

plurals
  1. POViolation reading location in std::map operator[]
    text
    copied!<p>I encountered a problem when running some old code that was handed down to me. It works 99% of the time, but once in a while, I notice it throwing a "Violation reading location" exception. I have a variable number of threads potentially executing this code throughout the lifetime of the process. The low occurrence frequency may be indicative of a race condition, but I don't know why one would cause an exception in this case. Here is the code in question:</p> <pre><code>MyClass::Dostuff() { static map&#60;char, int&#62; mappedChars; if (mappedChars.empty()) { for (char c = '0'; c &#60;= '9'; ++c) { mappedChars[c] = c - '0'; } } // More code here, but mappedChars in not changed. } </code></pre> <p>The exception is thrown in the map's operator[] implementation, on the very first call to the operator[] (Using the VS2005 implementation of STL.)</p> <pre><code> mapped_type& operator[](const key_type& _Keyval) { iterator _Where = this->lower_bound(_Keyval); //exception thrown on the first line // More code here } </code></pre> <p>I already tried freezing threads in operator[] and trying to get them to all run through it at the same time, but I was unable to reproduce the exception using that methodology.</p> <p>Can you think of any reason why that would throw, and only some of the time? </p> <p>(Yes, I know STL is not thread-safe and I'll need to make changes here. I am mostly curious as to WHY I'm seeing the behavior I described above.)</p> <p>As requested, here some further details about the exception:<br> Unhandled exception at 0x00639a1c (app.exe) in app15-51-02-0944_2008-10-23.mdmp: 0xC0000005: Access violation reading location 0x00000004.</p> <p>Thanks to everyone suggesting solutions to multithreading issues, but this isn't what this question is meant to address. Yes, I understand the presented code is not protected correctly and is overkill in what it's trying to accomplish. I already have the fix for it implemented. I'm just trying to get a better understanding of why this exception was thrown to begin with.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload