Multiple Root files, storing histo, closing file

Hello everyone!

I have multiple samples and therefore multiple input root files always containing one special histogram. I now want to open one file after another, read the histogram, store it, close the file, then in the end process the histograms and draw them.

  //Vector for histograms
  vector<TH2F*> histos;

 //example for 10 samples
 for(int k = 0; k < 10; k++) {
    //Open input file
    TString filename = "file"+k+".root";
    TString source ="MyInputDir/"+filename;
    TFile *file = TFile::Open(source);
    file->cd("MySubDir");

    string name = "sample"+k;
    string title = "My Title";
    TH2F *histo = (TH2F*)MyHistogram->Clone(name.c_str());
    histo->SetDirectory(gROOT);
    histo->SetNameTitle(name.c_str(),title.c_str());
    histos.push_back(histo);

    file->Close();
  }
[...further processing and drawing...]

So procedure:
(1) Create a vector to store the pointers for the histograms
(2) open a file
(3) Clone() the pointer for the needed histogram
(4) SetDirectory(gROOT) so that the histogram is still available after closing the file
(5) store the pointer in the vector
(6) closing the input file
(7) …moving to next input file…

Doing this procedure I get an SEGMENTATION VIOLATION while Cloning the Pointer for the histogram from the second (k=1) input file. Do I miss something here in C++ object and pointer organisation or do you know a better way for my problem?

PS: The file path for the second file is correct and the searched histogram is existing!

Hi,

Do you get this problem with compiled code or interpreted code?

Cheers,
Philippe.

PS. Also to avoid a memory leak, replace ‘file->Close();’ with ‘delete file;’

Sorry for not responding for so long…

I got this problem, when compiling the code. But I now found out, that the problem is caused by the root compiler. I now changed to an external compiler and run it externally, working fine.

so far!