Reputation: 1
I have the following method in C++ which checks the name at the map
map<string, bool> namesMap;
bool IsValidName(const char* name) {
string currentName(name, 16);
if (MapContains(namesMap, currentName))
return namesMap[currentName];
else
namesMap[currentName] = false;
return false;
}
template<class T, class K>
bool MapContains(const std::map<T, K>& targetMap, const T key) {
return targetMap.find(key) != targetMap.end();
}
Calling IsValidName() sometimes causes to capture the thread into an infinite loop. I've got a memory dump which shows that the thread is stuck in MapContains() method and further at xtree which is internally used by std::map.
All the names at the application are 6-8 characters long. So there is a bug at the line:
string currentName(name, 16);
Which causes all the checked names to have length: 16 instead of the correct one. As a result currentName has correct data in the first 6-8 chars and garbage at the rest ones. So the map is filled with 16-characters long strings with undefined data inside each of them.
Could this garbage cause the infinite loop while searching the map?
Or any other ideas what can cause it?
Update: As I've described above I know the problem with line:
string currentName(name, 16);
Just want to know how it causes map to have undefined behaviour
Upvotes: 0
Views: 1045
Reputation: 23813
Your program has undefined behavior.
The line string currentName(name, 16);
attempts to build of string of 16 characters from a const char*
pointing to 6-8 characters only.
Solution:
Provide at least 16 characters, or simply call string currentName(name);
Upvotes: 1