Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

string.clear() does not remove element properly

It seems that member function clear() of string does remove its content, but the removed contents still can be accessed by operator[] . Here’s the example that makes me confused.

#include <iostream>
using namespace std;
int main()
{
    string input = "Weird";
    cout << "Your Input: " << input << "\n";
    input.clear();
    cout << "Your Input: " << input << "\n";
    cout << "Your Input: " << input[0] << input[1] << input[2] << input[3] << input[4] << '\n';
    return 0;
}

The results are:

Your Input: Weird
Your Input:
Your Input: eird

Why this is happenning? If example above is normal, what should I do to completely remove its content? (accessing by input[1] should be ‘\000’)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Accessing elements of a string after calling the method clear invokes undefined behavior.

It seems in your case the class std::string uses its internal buffer defined within the class itself for short strings.

After the call of clear the class just set the first character of the buffer with the terminating zero character '\0;.

To check that string was cleared just output its length as for example

std::cout << input.length() << '\n';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading