我在C++中有以下方法,它在地图上检查名称
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();
}调用IsValidName()有时会导致将线程捕获到无限循环中。我有一个内存转储,它显示线程被卡在MapContains()方法中,在xtree上,xtree是std::map内部使用的。
应用程序中的所有名称都有6-8个字符长。因此,在行中有一个bug:
string currentName(name, 16);这将导致所有选中的名称都具有长度: 16,而不是正确的名称。因此,currentName在前6-8个字符中有正确的数据,在其余的字符中有垃圾。因此,映射中填充了16个字符的长字符串,每个字符串中都有未定义的数据。
在搜索地图时,这种垃圾会导致无限循环吗?
或者任何其他的想法是什么导致它的?
更新:,正如我前面所描述的,我知道行的问题:
string currentName(name, 16);只是想知道它是如何导致map具有未定义行为的。
发布于 2014-07-29 14:58:51
您的程序具有未定义的行为。
行string currentName(name, 16);试图从const char*构建16个字符的字符串,仅指向6-8个字符。
解决方案:
提供至少16个字符,或简单地调用string currentName(name);
https://stackoverflow.com/questions/25018334
复制相似问题