Search code examples
c++stringreplacereversestdstring

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 ?

solved: adding ch as a String adds a null terminator automatically, and by doing so we can get a new string with size+1.


Solution

  • 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.