iPherian iPherian - 1 year ago 76
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++) {

Compiled in

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download