TTree->Draw inside loop

Hello, I am getting an error running a program that uses several ttree->draw inside a loop and gets parameters of the plotted distributions. The minimal program I have been able to narrow it down to is


  TFile *a=new TFile("~diogo/RecAndMerge/protao18.root");
  TTree *pout=outTree;
  
  pout->Draw("G.Xfirst>>xf(1000,0,500)","","");
  cout << xf->GetMean() << endl;
  pout->Draw("G.Xfirst>>xf(1000,0,500)","","");
  cout << xf->GetMean() << endl;

  cout << "now the loop" << endl;

  for(int i=0; i<2; i++){

    pout->Draw("G.Xfirst>>xf(1000,0,500)","","");
    cout << xf->GetMean() << endl;
    cout << "feito " << i << " in " << 2 << endl;
      
  }

whose output is:

Info in TCanvas::MakeDefCanvas: created default TCanvas with name c1
46.6121
46.6121
now the loop
46.6121
feito 0 in 2

*** Break *** segmentation violation

===========================================================
There was a crash.
This is the entire stack trace of all threads:

#0 0x0000003d4f698c05 in waitpid () from /lib64/libc.so.6
#1 0x0000003d4f63c481 in do_system () from /lib64/libc.so.6
#2 0x00002ad9d2c48472 in TUnixSystem::StackTrace() ()
from /soft/lip-sw/cosmosw/Auger_Offline_x64/External/root/5.30.00/lib/root/libCore.so
#3 0x00002ad9d2c4525a in TUnixSystem::DispatchSignals(ESignals) ()
from /soft/lip-sw/cosmosw/Auger_Offline_x64/External/root/5.30.00/lib/root/libCore.so
#4

so the part outside the loop works but the one inside only works for the first element.
Also, commenting the cout << xf->GetMean() << endl; inside the loop solves the problem, but then i cent access any distribution parameter

Thanks,
F. Diogo

Try: [code]{
TFile *a = new TFile("~diogo/RecAndMerge/protao18.root");

#if 1 /* 0 or 1 /
// TH1F xf = ((TH1F)(gROOT->FindObjectAny(“xf”)));
TH1F xf = ((TH1F)(gDirectory->FindObject(“xf”))); // only in the current directory
if (xf) delete xf;
xf = new TH1F(“xf”, “xf”, 1000, 0, 500);
#else /
0 or 1 */
TH1F xf = new TH1F(“xf”, “xf”, 1000, 0, 500);
#endif /
0 or 1 */

TTree *pout; a->GetObject(“outTree”, pout);
if (!pout) { cout << “Warning: outTree NOT found!” << endl; }
else {
pout->Draw(“G.Xfirst>>xf”,"","");
cout << xf->GetMean() << endl;
pout->Draw(“G.Xfirst>>xf”,"","");
cout << xf->GetMean() << endl;

cout << "now the loop" << endl;

for(int i=0; i<2; i++){
  pout->Draw("G.Xfirst>>xf","","");
  cout << xf->GetMean() << endl;
  cout << "feito " << i << " in " << 2 << endl;
}

}
}[/code]

Works perfectly now, thank you!

Also, could you please explain what I was doing wrong in my first method? Seems to me like the part inside the loop was exactly like the one outside the loop, so I cannot understand the error.