Is this string splitting function OK?

[SIZE=2]Hello,

I am recently working on an application that sends large strings accross a network very often. These then need to be broken up first with '!' and then with ','. My current function (below) works fine for this when not too much data is being sent across the network but segfaults when a reasonable amount is sent across. Would anyone be so kind as to let me know if my function is flawed in some way and is causing the problem (such as memory leak etc...)
An example usage is...

string command = split_string(data, ",", 0);

The function is as follows...


string split_string(string input, string splitter, int number)
{
  int count = 0;
  string output;
  char* pch;
 
  for(int index = 0; index < input.length(); index++)
  {
    if(input[index] == splitter[0])
    {
      count++;
    }
  }
 
  if(count < number)
  {
    return "";
  }
 
  pch = new char[input.length() + 1];
  strcpy(pch, input.c_str());
  output = strtok(pch, splitter.c_str());
 

  for(int index = 0; index < number; index++)
  { 
    output = strtok(NULL, splitter.c_str());
  }
 
  return output;
}

Any help would be greatly appreciated!

Karsten

I have not go through the entire code.
But if you have multiple threads, then possibly strtok function is not thread safe.
Use strtok_r() .

I think the code can be more optimized.
There is no need of strtok or strtok_r() here for what you are doing :slight_smile:
you are checking for presence of the character in the input string and
you are traversing each and every character in it. so why can't you store from it directly
instead of using strtok().

It's not possible to answer that question until the innards of the string typedef are known. What are its member elements? Maybe all you need is a bigger buffer.

I was indeed using threads and using strtok_r instead seems to have fixed the problem.

Thank you everyone for your help :slight_smile: