Issue loading two TFiles in function!

Hello ROOT,

just another lost newbie here. I’m trying to access two TH1D histograms stored in two different root files within a function, but am having issues loading the root files from within the function. With the basic test code below, the root files are not loading correctly (only 18 bytes of over 2000 are loading).
`
void myFunction(string file1, string hist1, string file2, string hist2){
TFile *f = new TFile(file1.c_str(), “READ”); // opens the root file
TH1F *h1 = (TH1F *)f->Get(hist1.c_str());

TFile *g = new TFile(file2.c_str(), "READ"); // opens the root file
TH1F *h2 = (TH1F *)g->Get(hist2.c_str());

cout << h1->GetNbinsX() << endl;
cout << h2->GetNbinsX() << endl;

delete f;
delete g;

}
`
give errors:

Error in <TBufferFile::CheckByteCount>: object of class TNamed read too few bytes: 18 instead of 2540 Error in <TBufferFile::CheckByteCount>: object of class TNamed read too few bytes: 18 instead of 2540
Strangely, I notice that if I simply use GetBinCenter(someInt_t) at some point in the function, the root files load properly. The code below works…
`
void myFunction(string file1, string hist1, string file2, string hist2){
TFile *f = new TFile(file1.c_str(), “READ”); // opens the root file
TH1F *h1 = (TH1F *)f->Get(hist1.c_str());

TFile *g = new TFile(file2.c_str(), "READ"); // opens the root file
TH1F *h2 = (TH1F *)g->Get(hist2.c_str());

cout << h1->GetNbinsX() << endl;
cout << h2->GetNbinsX() << endl;

Double_t blah;
blah = h1->GetBinCenter(3);

delete f;
delete g;

}
`
I would greatly appreciate it if somebody could help me make sense of this!
best, jss

Hello @jss,

one thing you should always do after loading something from the file is to check if the pointers are actually not nullptr. It could be that the names are wrong, the type is wrong etc.
Next, I would advise to always use:

TH1F* myHisto;
file->GetObject("objectName", myHisto);

Now, the function will even check that the object with name myHisto can be converted to a TH1F. Maybe it’s a TH1D after all??
Again, after retrieving them with GetObject, please check the pointer.

Finally:
Do you try to use the histograms outside of the functions? I see that you are deleting the files at the end, which will also delete the histograms.

If all that checks out, I would say that the file is corrupt.

Hi Stephan,
Thanks for the response! Switching to the method you suggested seemed to fix the problem…

I think I mis-typed in my original post, the histograms in the root files really were TH1F’s which I just verified. I’m still not sure why the files were loading incorrectly before, but ill take this as victory. About using the histograms outside of the function: no, I just needed to do some computations in the function with the histograms:)

Thanks!