0

I am creating an array of c strings from a vector of strings. I want the resulting array to skip the first element of the vector. The function I am using for this is as follows:

char** vectortoarray(vector<string> &thestrings)
{
  //create a dynamic array of c strings
  char** temp = new char*[thestrings.size()-2];

  for(int i = 1; i < thestrings.size(); i++)
    temp[i-1] = (char*)thestrings[i].c_str();

  return temp;
}

I know that this code works, as I tested it in a smaller program without error. However, when are run in inside of a marginally larger program, I get the error terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc.

How do I keep this from happening?

conrosebraugh
  • 173
  • 2
  • 13

2 Answers2

0

That -2 definitely should not be there. Observe also that you have only allocated an array of pointers to each character array. You also need to allocate memory for the character arrays themselves.

0

I cannot say for certain, but your code CAN throw a bad_alloc when you call new with negative value. If you pass your function an empty vector for example, you are effectively calling

char** temp = new char*[-2];

so you should check this before calling new. From a logical perspective this inclusion of -2 makes little sense anyway. I would also suggest reading this question and answer Why new[-1] generates segfault, while new[-2] throws bad_alloc?

Community
  • 1
  • 1
mathematician1975
  • 21,161
  • 6
  • 59
  • 101