-3

enter image description hereWhen i am using StrSplit function with a constant string it works great. but when i read the line from a file and then use it as string for StrSplit function my program crashes. the following is the code and the error screen shot.

string Read_from_file(){

//load the text file and put it into a single string:
std::ifstream in("test.txt");
std::stringstream buffer;
buffer << in.rdbuf();
std::string test = buffer.str();
std::cout << test << std::endl << std::endl;
return test;
}
// split the given string according to give delimeters
vector<string> &StrSplit( string inStr, string sepStr, vector<string>       &outStrVec) {
char * comp;
char * buffer = new char[ strlen( inStr.c_str() ) ];
strcpy( buffer, inStr.c_str() );
comp = strtok ( buffer, sepStr.c_str() );
while ( comp != NULL ) {
    outStrVec.push_back(comp);
    comp = strtok ( NULL, sepStr.c_str() );
}
delete[]  comp;
delete[]  buffer;
return outStrVec;
}

vector<string> StrSplit( string inStr, string sepStr ) {
vector<string> outStrVec;
return StrSplit( inStr, sepStr, outStrVec );
![enter image description here][2]}

int main( ) {
Read_from_file();
string fileinput = Read_from_file();
vector<string> v;
string inStr = fileinput;
v = StrSplit( inStr, "|#$ *@.&\"!^01" );
for (unsigned int i = 0; i < v.size(); ++i) {
    cout << v[i] << '\n';
}

}

H.Jerry
  • 31
  • 1
  • 7
  • For example if i use inStr="bob010101*******was*....there"; v = StrSplit( inStr, "|#$ *@.&\"!^01" ); on ouptut i will get (Bob was there) but when i use the string which i have parsed from file i got the error shown on image. – H.Jerry May 06 '15 at 10:57
  • I'm reluctant to start pointing out problems, because you need to go [pick up a good book](http://stackoverflow.com/q/388242/1171191). But when you create `buffer` from `inStr`, you don't leave space for the `NUL` at the end. – BoBTFish May 06 '15 at 10:59
  • @BoBTFish couldn't understand what you meant, will you please explain a bit more, or it will be awesome if you show it in code. thanks in advance – H.Jerry May 06 '15 at 11:08
  • Please format your code snippet properly. – Roger Lipscombe May 06 '15 at 11:09
  • @Barryj It's the same as Henrik's answer. – BoBTFish May 06 '15 at 11:17
  • @RogerLipscombe Sorry roger just checked that the code format has slipped i am just fixing it – H.Jerry May 06 '15 at 11:25

1 Answers1

1

The buffer is too small to contain the string including the terminating 0 character.

Change

char * buffer = new char[ strlen( inStr.c_str() ) ];

to

char * buffer = new char[ strlen( inStr.c_str() ) + 1];

And don't call delete on pointers you didn't new (remove delete[] comp).

Actually, I would never use strtok in C++.

Henrik
  • 23,186
  • 6
  • 42
  • 92