Note that there are some explanatory texts on larger screens.

plurals
  1. POSeg fault on C++ map access
    text
    copied!<p>I've come across a strange issue in some code that I'm working on. Basically what's going on is that whenever I try to get some information from an empty map, the program segfaults. Here's the relevant code: (note that struct Pair is a data structure that is defined earlier, and sendMasks is a std::map that is good)</p> <pre><code>std::map&lt;std::string*, struct Pair*&gt;::iterator it; for(it = sendMasks-&gt;begin(); it != sendMasks-&gt;end(); it++){ //segfault //(some code goes here) } </code></pre> <p>I know that the pointer to the map is good; I can do </p> <pre><code>it = sendMasks-&gt;begin(); it = sendMasks-&gt;end(); </code></pre> <p>before my loop, and it doesn't segfault at all then.</p> <p>Now, if I put the following test before the for loop, it will segfault:</p> <pre><code>if( sendMasks-&gt;empty() ) </code></pre> <p>As will any other attempt to determine if the map is empty. </p> <p>This issue will only occur if the map is empty. My only thought on this issue would be that because I am updating sendMasks in a separate thread, that it may not have been updated properly; that however doesn't make any sense because this will only happen if the map is empty, and this code has worked perfectly fine before now. Any other thoughts on what could be happening?</p> <p><strong>EDIT:</strong> I figured out what the problem was.</p> <p>At an earlier part in my code, I was making a new char* array and putting that pointer into another array of length 4. I was then putting a NULL character at the end of my new array, but accidentally only did a subscript off of the first array - which went off the end of the array and overwrote a pointer. Somehow, this managed to work properly occasionally. (valgrind doesn't detect this problem) </p> <p>The sequence was something like this:</p> <pre><code>object* = NULL; //(overwritten memory) object-&gt;method(); //Inside object::method() : map-&gt;size(); //segfault. Gets an offset of 0x24 into the object, //which is NULL to begin with. memory location 0x24 = invalid </code></pre> <p>I wasn't expecting the instance of the object itself to be null, because in Java this method call would fail before it even did that, and in C this would be done quite differently(I don't do much object-oriented programming in C++)</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