I am confused about the used of Clone() for copying histograms. I would have thought it makes a copy in memory of a histogram read from a file, so that the cloned histogram can still be accessed when the file is closed. However, I get a segmentation fault if I try to access a cloned histograms after the file containing the original histogram is closed. Here is a simple root script which illustrates this problem:
#include <TFile.h> #include <TH1F.h> #include <TPad.h>
int test( void ) {
TFile *f = new TFile( “test.root” );
TH1F *h = (TH1F *) gDirectory->Get(“EML1A01_SegmentResidual”);
TH1F hist_new=(TH1F)h->Clone();
hist_new->SetName(“hist_new”);
// f->Close(); //crash if close file here
hist_new->Draw();
gPad->Print(“hist_new.png”);
// f->Close(); //no crash if close here
return 0;
}
How can I make a copy of a histogram from a file that I can access even after the file is closed?
I am using ROOT 5.26/00b
int test( void ) {
TFile *f = new TFile( “test.root” );
TH1F *h = (TH1F *) gDirectory->Get(“EML1A01_SegmentResidual”);
h->SetDirectory(0); // “detach” the histogram from the file
f->Close();
h->Draw();
gPad->Print(“h.png”);
return 0;
}
[/code]
See the users guide on ownership.
Use the static method TH1::SetDirectory(nullptr) before creating (or reading from file) any histogram. And please don’t reply to old topics, but create new ones instead