1

Why this program crashes? It crashes on line vec[0].assign("blabla");:

#include <vector>
#include <string>
using namespace std;

int main()
{
     vector<string> vec;
     vec.reserve(5);
     vec[0].assign("blabla");
}

Or this:

#include <vector>
#include <string>
using namespace std;

int main()
{
    vector<string> vec;
    vec.reserve(5);
    vec[0].push_back('a');
}

And what is best to use instead of if it really doesn't work?

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
Scarass
  • 914
  • 1
  • 12
  • 32

1 Answers1

1
vector<string> vec;
vec.reserve(5);
vec[0].assign("blabla");

This causes undefined behavior. vec[0] has been reserved but not allocated. You should use push or emplace instead.


vector<string> vec;
vec.reserve(5);
vec[0].push_back('a');

Same error. You are pushing to vec[0] which is not exist in memory yet.


Solution:

vector<string> vec;
vec.reserve(5);
vec.emplace_back("blabla"); //or push_back

Or:

vector<string> vec;
vec.resize(5);// Notice resize not reserve
vec[0].assign("blabla");//this works now since vec[0] is exist

Or:

vector<string> vec;
vec.resize(5);// Notice resize not reserve
vec[0].push_back('b'); //this works now since vec[0] is exist

I do NOT prefer the second option since it causes construction N times then assignment N times

Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160