0

I encountered some weird behavior of insert function for std::vector using iterators.

What I'm trying to do is basically input the strings from text file in the alphabetical order, but when I use std::vector::insert function with strings I get an Segmentation fault (core dumped) message. std::vector::push_back works without any problems.

In other words, performing operation like this works:

std::vector<int> intVec;
intVec.push_back(1);
std::vector<int>::iterator it = intVec.begin();
intVec.insert(it, 5);

And operation like this causes the Segmentation fault:

std::vector<std::string> strVec;
std::vector<std::string>::iterator it = strVec.begin();
strVec.push_back("some string");
strVec.insert(it, "some other string");

Inserting using variables like std::sting var = "some string" does not work either, nor using c_str() function.

Does anyone possibly knows why that problem may occur? Thanks for any explanation.

P.S. I can solve sorting problem using different mechanisms, just want to figure out what's going on here.

Huu
  • 1
  • 2
  • 1
    Your codes are not the same. Look at when you declare the iterator. In the string case you do it before the invalidating operation – NathanOliver Feb 07 '19 at 16:37
  • @NathanOliver Okay so as I understand it, when vector is empty, it has no address in memory at all, shouldn't it at least have allocated enough memory to hold at least one std::string so it can actually have a base address? – Huu Feb 07 '19 at 16:55
  • It could, but most implementations don't. It could be wasteful to do so. Generally a default constructed vector will have a capacity of 0. – NathanOliver Feb 07 '19 at 16:57
  • @Huu in general (it is implementation dependent) the vector stores the elements in separate allocated memory on the heap, and holds a pointer to that allocated memory. If an empty vector is created then no separate memory is allocated and it’s internal memory address points to `nullptr`, when the first element is push the vector will allocate memory to store that element. – t.niese Feb 07 '19 at 17:05
  • That changes a lot! Thanks for answering my questions. – Huu Feb 07 '19 at 17:06
  • As I see now, I could use std::vector::reserve to increase capacity and it works fine as well. – Huu Feb 07 '19 at 17:32

0 Answers0