CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Mar 2006
    Posts
    6

    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?

  2. #2
    Join Date
    Feb 2005
    Location
    "The Capital"
    Posts
    5,306

    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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured