简体   繁体   中英

String Rev function, strange behavior for out of bounds exception (c++)

I played with the string function,i wrote the following one, obviously I set the first character in the ret string to be written in a place that is out of bounds, but instead of an exception, I get a string that has one extra place .

std::string StringManipulations::rev(std::string s)
{
    
    std::string ret(s.size(), ' ');

    for (int i = 0; i < s.size(); i++)
    {
        std::string ch;
        ch.push_back(s[i]);
        int place = s.size() -i;
        ret.replace(place,1,ch);
    }
    return ret; 
}

I write by mistake in a position that corresponds to a place that is one larger than the original string size that I assign at the beginning of the function.

Why don't we get an error ?

s = StringManipulations::rev("abcde");
    std::cout << s.size();
    std::cout << s;

output is : 6 _edcba 

any help ?

C++ has a zero-overhead rule. This means that no overhead, (like checking if an index is in-bounds) should be done unintentionally. You don't get an exception because c++ simply doesn't verify if the index is valid.

For the extra character, this might have something to do with (regular) c strings. In c, strings are arrays of type char (char*) without a defined size. The end of a string is denoted with a null terminator . C++ strings are backwards compatible, meaning that they have a null terminator too. It's possible that you replaced the terminator with an other character but the next byte was also a zero meaning that you added one more char.

In addition to the information above about null terminators, another answer to your question is that the docs says it will only throw if the position is greater than the string size, rather than beyond the end of the string. string replace api

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