I'm very confused with a simple but not understandable segmentation fault in my code.
I have something like this
1 2 3 4 5 6 7 8 9 10 11 12 13
typedef std::map<std::string, std::string> FilesMap;
FilesMap files;
...
FilesMap::const_iterator it = files.begin();
const FilesMap::const_iterator itEnd = files.end();
std::cout << "Size of the map is " << files.size() << "!!!!!!\n";
while (it != itEnd)
{
std::cout << "--------------------------\n";
++it;
}
The output is
Size of the map is 1!!!!!!
--------------------------
--------------------------
--------------------------
Segmentation fault
Can anybody explain what's going on here? Why std::cout in while cycle is called three times when the size of the map is 1 (I print the size exactly before iterating the map). This works fine when it is separated program, but in my code, where map of files comes from another class, I have segmentation fault. And the thing is that I don't have invalid fields in my map, but the program tries to access somewhere out of the map. But why? Is the condition in while understood wrongly?
Do you have any suggestions how I can resolve the problem? Where to start from? What to check?
There's nothing wrong with the code you posted here, which is why it works in your mini test app. The problem lies elsewhere.
The only ways I can see this happening is if 'Files' is somehow being modified after line 6.
This could happen if you are multithreading, or if you loop is doing something you're not posting here (like removing elements), or if 'Files' itself is being moved in memory (if it's in a vector or something that is being resized).
The code between line 6 and 13, that I have posted here, exactly is the same as in my real code.The only difference is that, instead of files map, I use files() function for some object,which returns the map.
I'm not multithreading nor my loop does anything else in my real code...actually it did something different, but to understand where the real problem was, I deleted everything apart from those lines.
I appreciate your help, if you have any ideas, I look forward to hearing from you!