Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ string size not updated after assignment

int main(int argc, char const *argv[])
{
    const char *s1 = "hello";
    string s2;
    s2 = s1;
    s2.reserve(10);
    s2[5] = '.';
    s2[6] = 'o';
    s2[7] = '\0';
    cout << "[" << s1 << "] [" << s2 << "]" << endl;
    return 0;
}

The above code does not print s2 correctly. Instead of hello.o it prints hello always. It seems like the size of s2 remains at 5 always after the first assignment. Why is this so?

like image 209
siri Avatar asked Feb 11 '16 07:02

siri


2 Answers

operator[] does not resize the string. And your calls to it with indices 5, 6 and 7 are out of range and undefined behavior. Use resize to set the string to a specific size, or push_back or operator+= to append characters.

Also note that you do not need to zero terminate std::string manually. The class will handle that by itself. Although you are allowed to have embedded zeros in there if you really want them, and they will be considered as part of the length of the string.

like image 132
Benjamin Lindley Avatar answered Oct 07 '22 05:10

Benjamin Lindley


s2.reserve(10); doesn't grow the string at all, it just tells the container to reserve enough memory for at least 10 characters. It does't fill the reserved space with anything.

Hence, when you index it s2[5] you essentially index outside the bounds of the "used" string (i.e. its size), it is undefined behaviour.

To resize, you can use s2.resize(10);. This will allocate and fill the string appropriately and it will have a size of 10. To allocate and insert a character at the same time, you could also use push_back() or operator+=.

On a side note: s2[7] = '\0'; is not needed. The string class manages internally any NUL terminations that are needed for methods such as c_str() etc. You don't need to add the NUL yourself.

like image 45
Niall Avatar answered Oct 07 '22 04:10

Niall