I am still moving from Java to C++ and I am struggling with strings. I need to generate some strings and store them somewhere so that they are available to my program after the object that created them is destroyed. I tried storing them in a vector of strings but I get a Segmentation Fault – double free. A basic version of what I am doing, and that reproduces the problem is here:
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
std::string makeString(){
std::stringstream s;
s << "Test string";
return s.str();
}
int main(){
std::vector<std::string> storage;
storage.reserve(1);
storage[0] = makeString();
return 0;
}
The debugger marks the error in the line:
storage[0] = makeString();
I will thank a lot and insight on what is going on here and how to avoid it, please.
vector.reservedoes not change the size of the vector. You will have to useresizeinstead ofreserve. Another option is to usepush_back():