Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does STL map core dump on find?

Tags:

c++

gcc

map

So, I have this situation where I need to see if an object is in my stl map. If it isn't, I am going to add it.

char symbolName[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
map<string,TheObject> theMap;
if (theMap.find(symbolName)==theMap.end()) {
            TheObject theObject(symbolName);
            theMap.insert(pair<string, TheObject>(symbolName,
                    theObject));
}

I am getting a core dump on the: theMap.find when the object is not already in the map. Supposedly, if the item is not in the map, it is supposed to return an iterator equivelent to map::end

What is going on here?

GCC: 3.4.6

like image 240
Alex Avatar asked Dec 03 '22 16:12

Alex


1 Answers

It can crash because of many reasons. Without knowing the definition of at least TheObject's constructors, i think we are largely left to guess at the problem. So far, your code looks fine, but it can be simplified:

char symbolName[] = "Hello";
map<string,TheObject> theMap;
theMap.insert(make_pair(symbolName, TheObject(symbolName)));

It won't do anything if the symbol is already mapped, discarding the new TheObject object.

like image 159
Johannes Schaub - litb Avatar answered Dec 09 '22 15:12

Johannes Schaub - litb