1

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.

2
  • A quick fix is to use resize instead of reserve. Trying to emulate a Java StringBuilder is not the greatest idea either. They are different languages. Commented Feb 8, 2013 at 12:42
  • I got no error when i compile this!.Can u post the error also? Commented Feb 8, 2013 at 12:46

1 Answer 1

5

vector.reserve does not change the size of the vector. You will have to use resize instead of reserve. Another option is to use push_back():

 storage.push_back(makeString());
Sign up to request clarification or add additional context in comments.

2 Comments

You can use reserve in conjunction with push_back (or the insert iterators, etc) if you wish to avoid reallocation during insertion.
Thanks! resize solved my problem. (I really need to use assignment instead of push_back).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.