【问题标题】:C++ string concatenation fails sometimesC++ 字符串连接有时会失败
【发布时间】: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


【解决方案1】:

感谢您的所有 cmets! 你激励我再看一遍所有东西,所以我发现了我的错误。 在一个只有 64 个位置的数组中设置第 65 个位置是一个简单的尝试。

之前,这段代码必须读取一组 64 个文件,现在我将其扩展为 109 个文件。 我只是忘了更新数组的大小,它保存了每个文件的信息。

我仍然不明白,为什么异常是在第 71 个索引而不是在第 65 个索引引发的,以及为什么它发生在字符串连接而不是数组操作中,但至少代码现在似乎可以工作.

【讨论】:

    猜你喜欢
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多