Click to See Complete Forum and Search --> : splitting strings memory glibc kinda problem


_sluimers_
March 2nd, 2006, 06:10 AM
vector<char*> * Program::StringSplit(char * str, char * delim){
vector<char*> * results = new vector<char*>;
char * word;
word = strtok (str,delim);
results->push_back(word);

while (word != NULL){
word = strtok (NULL, delim);
if(word != NULL){
results->push_back(word);
}
}
return results;
}

It works with a string of one word and sometimes two.
Using more words and one of the words are no longer accurate.

But when using 7 words this is the first line of the very long error I get:
*** glibc detected *** ./shell: free(): invalid next size (normal): 0x08264300 ***

I'm not that good at programmnig. All I know is that is has memory problems.
What is wrong with this code and how should it be fixed in order to correctly split
strings?

exterminator
March 2nd, 2006, 07:47 AM
That code is wrong.. it will not work..

Use std::string instead of char arrays and put a std::string object in the vector and not a pointer...

So the vector would have a declaration like this:

std::vector<std::string> vec_;
Also, pass that vector as an argument by reference to that function. Dont do dynamic allocation - to just make the vector live outside that function. It also asks for the caller to clean-up the dynamic allocations. Very bad practice.