Cloning histograms

Hello, everyone:

I am learning how ROOT works by coding simple examples, and I stumbled on an example I don’t understand. I make a file called “Ejemplo4a.cpp”, which creates a simple histogram and fills it randomly:

[code]{

TH1F *hist2 = new TH1F(“hist2”, “Histograma Ejemplo 4a”, 100, 0.0, 1.0);
hist2->SetMinimum(0.0);

//LLenamos el histograma al azar:
gRandom->SetSeed(0);
double r = 0.0;

for(int i = 0; i < 1000; i++)
{
r = 3.1415*gRandom->Rndm(1);
hist2->Fill( sin® );
}

TFile *f1 = gROOT->FindObject(“ejemplo4a.root”);
if (f1) f1->Close();
f1 = new TFile(“ejemplo4a.root”,“recreate”);

hist2->Write();

f1->Close();

}[/code]

The previous is executed with “.X Ejemplo4a.cpp”. Then, I create a different file which reads the file, clones the histogram from “ejemplo4a.root”, and draws it:

[code]{

TFile *f = gROOT->FindObject(“ejemplo4a.root”);
if (f) f->Close();
f = new TFile(“ejemplo4a.root”,“read”);

TH1F histNuevo = (TH1F)hist2->Clone(“histNuevo”);
//f.Close();

histNuevo->Draw();

}[/code]

I execute it with “.X Example.cpp”. The problem occurs when I uncomment the line:

If this line is executed, ROOT crashes ("*** Break *** segmentation violation").

Why does ROOT crash? If I cloned the histogram, I should be able to close the file and draw the clone.

Thanks!

[quote]Why does ROOT crash? If I cloned the histogram, I should be able to close the file and draw the clone.[/quote]Nope … See the User’s guide chapter on objet ownership. In you case since ‘f’ is the
current ROOT directory when you clone, it belongs by default to ‘f’ and is deleted when ‘f’ is closed.{ TFile *f = gROOT->FindObject("ejemplo4a.root"); if (f) f->Close(); f = new TFile("ejemplo4a.root","read"); TH1F *histNuevo = (TH1F*)hist2->Clone("histNuevo"); histNuevo->SetDirectory(0); // Disassociate the histogram from the directory, we now owner this histogram. f.Close(); histNuevo->Draw(); } will work. (you could also simply try hist2->DrawClone();

Cheers,
Philippe.

PS. you could also