【发布时间】:2018-12-01 13:47:41
【问题描述】:
我是 C++ 的血腥初学者。 我尝试读取序列号文件。为此,我必须创建字符串来包含文件名和升序文件索引。
我的代码适用于 70 以下的索引。当索引为 71 时,突然抛出异常。
这是我的代码:
for (int i = 0; i < 110; i++)
{
std::string index = std::to_string(i);
std::string filenameA = "fileA"+ index + ".png"; // Here the Exception is thrown
std::string filenameB = "fileB"+ index + ".png";
std::string filenameC = "fileC"+ index + ".png";
...
}
当i=71 我遇到读取访问冲突。
该方法在文件xutility中抛出异常:
inline void _Container_base12::_Orphan_all() noexcept
{ // orphan all iterators
#if _ITERATOR_DEBUG_LEVEL == 2
if (_Myproxy != nullptr)
{ // proxy allocated, drain it
_Lockit _Lock(_LOCK_DEBUG);
for (_Iterator_base12 **_Pnext = &_Myproxy->_Myfirstiter;
*_Pnext != nullptr; *_Pnext = (*_Pnext)->_Mynextiter)
(*_Pnext)->_Myproxy = nullptr;
_Myproxy->_Myfirstiter = nullptr; // Here the exception is thrown
}
#endif /* _ITERATOR_DEBUG_LEVEL == 2 */
}
奇怪的是,如果".png" 中的. 缺失,代码可以正常工作。
另外,如果我更改文件的顺序,例如这样
std::string filenameB = "fileB"+ index + ".png";
std::string filenameC = "fileC"+ index + ".png";
std::string filenameA = "fileA"+ index + ".png";
错误仍然发生在std::string filenameA = "fileA"+ index + ".png";
我真的不明白,为什么在这种特殊情况下字符串连接失败。
【问题讨论】:
-
问题可能出在代码的其他地方。如果你在其他地方破坏了堆,任何事情都可能发生。请发布minimal reproducible example 和完整的错误消息。谢谢!
-
是的——请记住,在 C++ 中,程序的一部分如何破坏另一部分的行为的可能性是无穷无尽的。您可能会在程序的“...”部分以某种方式破坏内存,然后转身并绊倒原本完全有效的代码。所以你的问题需要是一个完整的程序——有一个 main() 和
#includes 和所有东西——其他人可以编译和重现你的效果。但它应该被最小化到只需要得到错误的代码量——即使错误发生在 71,也不要一直计数到 110! -
你使用什么编译器?您的代码是正确的,必须有效。
标签: c++ string concatenation