I have a program I'm working on for a class. We have to break a file
up into all of the "words" in a file, and then insert each word into
an ordered list. If the word is already in the list we increment the
count of the node rather than inserting a duplicate. When it's
finished we output the list of all the "words" in the file and the
number of times each word occurred. I've got most of it complete, but
have one problem...
we're working with gnu's gcc compiler and we're not allowed to use STL
or the string class(we essentially have to create our own) in
microsoft c# I know there is a string.split(delims) method, I'm
basically trying to duplicate it in my string class and here's what I
have....
myString *myString::split(int &tokenCount,const myString &delim)
{
myString *tokens=NULL;
char *temp;
char *saveData=new char[length+1];
strcpy(saveData,data);
tokenCount=0;
temp=strtok(saveData,delim.data);
while(NULL!=temp)
{
tokenCount++;
temp=strtok(NULL,delim.data);
}
if(tokenCount>0)
{
tokens=new myString[tokenCount];
strcpy(saveData,data);
tokens[0]=strtok(saveData,delim.data);
for(int i=1;i<tokenCount;i++)
{
tokens[i]=strtok(NULL,delim.data);
}
}
return tokens;
}
The above code seems to work for all my tests, but I'm worried with
the dynamic memory allocation of the return that I'm leaking memory.
Which of course is bad practice, and will get me an automatic zero on
the assignment. I'm looking for a solution where I can return the
array of tokens, rather than pass the token array in by reference. Is
that impossible without leaking memory in the process? and without
using global scope variables?


|