Search code examples
c++stringstdstdvector

Using std::vector::insert to string into vector of uint8_t puts random data in it


I'm serializing data into a vector of uint8_t to send it to another module, I have a string that it returned from a function getVal() and when I do vector.insert() it it shows random vals more into my vector.


std::string getVal() 
{
    std::string x = "564";
    return x ; 
}

int main() 
{ 
    std::vector<uint8_t> data {0x70}; 

    data.insert(data.end(),getVal().begin(),getVal().end());

    for (auto i:data)
        std::cout << i <<std::endl; 
    
    std::cout<<data.size()<<std::endl;
    std::cout << getVal() <<" ,type: "<< sizeof(getVal()) << ", .size(): "<< getVal().size()<<std::endl; 


    return 0; 
}

Appreciate your help.

The solution was to loop over the string and use .push_back(), but I need to understand why this happened with .insert().


Solution

  • Because getVal Return by value, the two calls will return two different and unrelated std::string objects.

    The begin and end iterators of those objects will be related to different objects, and using them together will lead to undefined behavior.

    Either you need to create a static string, and return a reference to it. Or you need to store the string that getVal returns and use that object.