Home > Back-end >  Why does std::string store content at the same address inside a loop?
Why does std::string store content at the same address inside a loop?

Time:01-09

I need to create a char[] dynamically. I would like to use std::string instead of working on char[] directly since I don't need to take care of the memory management with std::string. Here is my example code:

int main()
{
    std::vector<char*> char_vec;
    for(size_t i = 0; i < 10; i  )
    {
        std::string s;
        s = "test"   std::to_string(i);
        char_vec.push_back(const_cast<char*>(s.c_str()));
    }

    for(auto& ele : char_vec)
    {
        std::cout << ele << std::endl;
    }
}

The output is: enter image description here, which is not what I want.

In my understanding, the string s created inside the loop should be completely new in every iteration, but in fact, all strings use the same address to store the content. Why does this happen? How should I modify my code to achieve my target?

Thank you for all the help!

CodePudding user response:

Storing the s.c_str() pointers in the vector, when the s lives only until the end of the loop iteration, will cause undefined behavior, at latest when you try to read through these pointers.

It is immaterial whether the pointers have the same value. As soon as the scope of s ends, they become invalid. The memory they address can then be reused for whatever by the compiler/library. You are not guaranteed to be able to read anything sensible from them at all. That you got even test9 back was "luck".

You should be using a std::vector<std::string> and then just char_vec.push_back(s); (or if you want to optimize char_vec.push_back(std::move(s)), but only because you do not use s after the push_back).

  • Related