Dear Rooters
I apologize for asking a mainly C/C++ question, but I am not sure whether my function:
TString Path2Name(const char *name, const char *sep, const char *exten)
which I use at many places in my program, is really correct.
Here are some examples how I use this function:
root [1] Path2Name("/my/path/to/myfile.root", "/", "")
(class TString)"myfile.root"
root [2] Path2Name("/my/path/to/myfile.root", "/", ".")
(class TString)"myfile"
root [3] Path2Name("/my/path/to/myfile.root/mytree.txt;1", "/", "")
(class TString)"mytree.txt;1"
root [4] Path2Name("/my/path/to/myfile.root/mytree.txt;1", "/", ";")
(class TString)"mytree.txt"
root [5] Path2Name("/my/path/to/myfile.root/mytree.txt;1", "/", ".")
(class TString)"mytree"
root [6] Path2Name("/my/path/to/myfile.root/mytree.txt;1", "", ".root")
(class TString)"/my/path/to/myfile"
Here is the source code:
TString Path2Name(const char *name, const char *sep, const char *exten)
{
// Extract name from full path
// sep is path separator and exten is name extension
TString outname = TString(name);
char *tmpname = new char[strlen(name) + 1];
char *delname = tmpname;
tmpname = strtok(strcpy(tmpname,name),sep);
while(tmpname) {
outname = tmpname;
tmpname = strtok(NULL,sep);
}//while
if (strcmp(exten,"") != 0) {
Int_t i = outname.Index(exten);
if (i > 0) {outname = outname.Remove(i);}
}//if
delete [] delname;
return outname;
}//Path2Name
I am using this function in my program for a long time without any problems, but
recently I get strange results when working with large datasets resulting in very low
memory conditions. For example, when exporting all tree names from a file, one of the
trees returns as name e.g.:
"H\207\200\001H\207\200\001H\207\200\001H\207\200\001H\207\200\001H\207\200\001H\207\200\001H\207\200\001H\207\200\001H\207\200"
I am not sure what could be the reason for this, but to me it looks as memory overflow,
so my questions for the moment are:
- Is the code for function Path2Name() correct?
- Is the line “delete [] delname;” correct?
- What happens if I delete line “delete [] delname;”? (I see no difference)
- Does the returned “outname” have a valid memory?
Thank you in advance.
Best regards
Christian