Pointer returned from macro function is losing content

In ROOT 6.08/06, I am running a fairly simple macro. It takes two arguments to open a file and find a TTree in that file. Once I have the TTree*, I can pass it around to do other things (plotting, etc.).

The problem I have is that the pointer which gets returned by my function is corrupt. Here’s the function code, including debugging output:

TTree* getTree(const TString& fname, const TString& type) {
  TFile file(fname);
  if (!file.IsOpen()) {
    std::cerr << "ERROR opening " << fname << std::endl;
    return 0;
  }

  TString treestr = "G4SimDir/g4dmc"+type;
  const char* treename = treestr.Data();
  std::cout << "Looking for " << treename << " in " << file.GetName()
	    << std::endl;

  TTree* tree = 0;
  file.GetObject(treename, tree);

  std::cout << "Got object @ " << tree << " of type " << tree->ClassName()
	    << " named " << tree->GetName() << std::endl;
  
  return tree;
}

Here’s the top-level macro where it gets called, along with a debugging statement:

int G4DMCtrace(const TString& fname, const TString& type,
	       Long64_t evt, Int_t chan) {
  TTree* tree = getTree(fname, type);
  if (!tree) return 2;

  std::cout << "In main, tree @ " << tree << " of type " << tree->ClassName()
	    << " named " << tree->GetName() << std::endl;

And finally, here’s what gets printed out when I run it. The file itself is valid (I can open it in TBrowser and the content I expect is all there):

{michaels-mbp:260} root -l -q -b G4DMCtrace.C'("TES_10180328_0000.root","TES",0,0)' | & more

Processing G4DMCtrace.C("TES_10180328_0000.root","TES",0,0)...
Looking for G4SimDir/g4dmcTES in TES_10180328_0000.root
Got object @ 0x7f88cfe4ba20 of type TTree named g4dmcTES
In main, tree @ 0x7f88cfe4ba20 of type TObject named TObject

 *** Break *** segmentation violation
[<unknown binary>]
[<unknown binary>]

Notice that the pointer address returned is the same as it was inside the getTree() function, but the information content (ClassName, tree name, etc.) are hosed.

Never mind. The performance is as expected, because I wrote my function with a TFile file declaration, instead of TFile *file = new TFile. When file goes out of scope, the extracted pointers are no longer guaranteed to be valid.