Passing TH1* From Function Gives Access Violation Error

I have a large number of root files containing several histograms each, which I can view and manipulate fine in a TBrowser. I have attached an example file. I can also load them in code as a TH1D*, but as soon as they are returned from the loading function their TArrayD becomes null, and starts causing access violation errors.

The following code snippet produces the error at the call to GetBinContent. I’ve tested a couple of other functions as well. GetBinCenter gave the same error, but GetXaxis worked as expected.

TH1D* testLoad() {
	TFile f("C:\\Path\\To\\File\\RootFile.root");
	TH1D* hist = (TH1D*)f.Get("hGeTotEGauss2");
	return hist;
}

void testSnippet() {
	TH1D* hist = testLoad();
	double value = hist->GetBinContent(1185);
	std::cout << value << std::endl;
}

If the histogram is loaded in the same function as it is used (as in the below snippet), there is no problem.

void testSnippet() {
	TFile f("C:\\C:\\Path\\To\\File\\RootFile.root");
	TH1D* hist = (TH1D*)f.Get("hGeTotEGauss2");
	double value = hist->GetBinContent(1185);
	std::cout << value << std::endl;
}

Is this a known bug? And is there anything simple I can do to get round it?

_ROOT Version: v6.26.04
_Platform: Windows C++
_Compiler: Visual Studio

SimLuna.1.root (134.5 KB)

TH1D* testLoad() {
   TFile f("SimLuna.1.root");
   TH1D* hist = (TH1D*)f.Get("hGeTotEGauss2");
   hist->SetDirectory(0);
   return hist;
}

void testSnippet() {
   TH1D* hist = testLoad();
   double value = hist->GetBinContent(1185);
   std::cout << value << std::endl;
}

That works perfectly, thank you!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.