Use of TH1->Clone()

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

I’ve attached test.root containing the histogram.

Thank you.
test.root (7.69 KB)

Hi,

No need to clone it, just call h->SetDirectory(0) to keep it from being deleted when the file closes:

[code]#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”);
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.

Cheers, Bertrand.

Dear Bertrand,

Thanks for the information. I did not know about the SetDirectory() business.

best regards, Edward Diehl

Hi Edward,

You’re very welcome. And FYI, you can also use this syntax: TH1::AddDirectory(kFALSE) to disconnect any histogram from the file.

Cheers, Bertrand.