iPherian iPherian - 2 months ago 7
C++ Question

C++ vector of strings segfault

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

Answer

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));