简体   繁体   中英

C++ string concatenation fails sometimes

I am a bloody beginner with C++. I try to read serially numbered files. For that purpose, I have to create strings for containing file names with a ascending file index.

My code works for indices under 70. When the index is 71 suddenly a exception is thrown.

Here's my code:

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";

    ...
}

When i=71 I get a reading access violation. The exception is thrown in the file xutility at this method:

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 */
    }

Strangely, the code works without problems if the . in the ".png" is missing. Additionally, if I change the order of the files, for example like this

std::string filenameB = "fileB"+ index + ".png";
std::string filenameC = "fileC"+ index + ".png";
std::string filenameA = "fileA"+ index + ".png";

the error still happens at std::string filenameA = "fileA"+ index + ".png";

I really don't get, why the string concatenation fails for this special case.

Thanks for all your comments! You inspired me to look over everything one more time, so I found my mistake. It was a simple try to set the 65th place in an array which had only 64 places.

Earlier, this code had to read a set of 64 files, now I expanded it to 109 files. I just forgot to update the size of my array, which saves information for each file.

I still don't understand, why the exception was thrown at the 71st index and not at the 65th index and why it happend at the string concatenation and not at the array-operations, but at least the code seems to work now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM