|
-
March 2nd, 2006, 07:10 AM
#1
splitting strings memory glibc kinda problem
Code:
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?
-
March 2nd, 2006, 08:47 AM
#2
Re: splitting strings memory glibc kinda problem
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:
Code:
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.
Can you help me with my homework assignment?, Before you post!, Use code tags, How to post!, Codeguru technical FAQs, C++ FAQ Lite, Stroustrup: C++ Style and Technique FAQ, Guru of the Week, Comeau C and C++ FAQs, Comeau C++ Templates FAQs, CUJ @ DDJ, Spam threshold
My Blogs : Learning C++ is fun | Abnegator's reflections
Open Threads : C++ Aha! Moments | Nature of work in C++?
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|