-6

can anyone tell me why this segfaults?

vector<string> vec;
for (int i = 0; i < 1000000; /* 1 million */ i++) {
    vec.push_back("string"+i);
}

Compiled in g++ with -std=c++14

sunkuet02
  • 2,376
  • 1
  • 26
  • 33
iPherian
  • 908
  • 15
  • 38

2 Answers2

4

As panta-rei correctly pointed out, it looks like you're trying to contain a string of the form

"string" + string form of (i)

but you're actually doing pointer arithmetic which is illogical in this case (you're just passing a pointer incremented i from some location - who knows what's in that memory?).

In order to do what you want, you can use std::to_string, which will translate i to a proper C++ string. The addition of a C-style string with that, is OK.

Change your line to

vec.push_back("string"+to_string(i));
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
2
vector<string> vec;
for (int i = 0; i < 1000000; i++) {
    vec.push_back("string" + to_string(i));
}

this is not PHP...

Frederick Zhang
  • 3,593
  • 4
  • 32
  • 54