TString returning garbage from TString::Data()

Hi,

I use root version 5.10 and I have a strange problem with TStrings. I declared a function that combines TStrings and returns the const char* TString::Data() member of the combined string. Occasionally, the output gets garbled. Here is the simplest version I could make of the problem (also attached) and below it is the output:

void run() 
{
  for(int i = 0; i<10; i++) {
    cout << getName(i) << endl;
  }
};

const Char_t* getName(Int_t n) 
{
  TString name = TString("h");
  name += n;
  return name.Data();
};

The commands and output:

Clearly the h0 got garbled. Any thoughts?

Thanks,

Robert

P.S. I just tried this with root 4.00.08 and it also got garbled but with a different character output:

TStringProblem.C (201 Bytes)

const Char_t* getName(Int_t n) { TString name = TString("h"); name += n; return name.Data(); }; This can not work because the memory returned by name.Data() is held by the object ‘name’ and is freed when the function returns. As any already delete memory access, the behavior is random.

Cheers,
Philippe

Hi,

I figured that it was something like that. However, is there a simple solution to get this to work? Basically, what I use is a more complicated version that involves a lot more input parameters. I do this to give every object that I name a unique name based upon the set of parameters that I feed it. Each object can then be accessed on a TClonesArray through the FindObject() method. It seems as though this should be possible, and easy.

Thanks,

Robert

Well no knowing the rest of your code, the simpliest solution is:

TString getName(Int_t n) { TString name("h"); name += n; return name; };

Cheers,
Philippe

Hi,

Thanks, I had already started doing that. I wanted to avoid having to to do getName().Data() everytime I wanted the name, but it looks like I have to return the TString instead of a const char*. Oh, well.

Thanks,

Robert

Alternatively you can replace you getName(n).getData();byForm("h%d",n);.
Also note that in most case (except variadic function like printf), you can use the TString where a const char* is expected.

Cheers,
Philippe.