Search code examples
c++vectorc-strings

Cannot push C style strings into std::vector


I'm trying to push some const char* into a vector, but the vector remains unpopulated after performing the operations I would presume to fill it.

Here's my attempt, where dict is my command-line argument.

test.cc

#include <iostream>
#include <string>
#include <vector>
#include <fstream>

using namespace std;

int main(int argc, char **argv) 
{
  ifstream dict;
  size_t dict_size;

  dict.open(argv[1]); // Dictionary

  vector<const char*> dictionary; 

  string line;
  getline(dict, line);

  while(!dict.fail()) {
    dictionary.push_back(line.c_str());
    getline(dict, line);
  }

  dict_size = dictionary.size();

  for(int i = 0; i < dict_size; i++)
      cout << "dictionary[" << i << "] is " << dictionary[i] << endl;
}

dict

Hello
World
Foo
Bar

After compiling this, I get the following output:

dictionary[0] is 
dictionary[1] is 
dictionary[2] is 
dictionary[3] is 

However, if I change the dictionary's type to vector and push back line instead of line.c_str(), I get the expected output:

dictionary[0] is Hello
dictionary[1] is World
dictionary[2] is Foo
dictionary[3] is Bar

I'm not terribly familiar with C style strings, so maybe it has something to do with null termination?


Solution

  • You are storing dangling pointers.

    std::string::c_str() isn't a pointer to some permanent copy of data — just think, that would be leaked!

    Store the std::strings instead.