Memory issues while loading 2D histograms by opening multiple .root files

Hi all,

I am trying to load multiple 2D histos in a root macro and using the function

TH2* Load2DHist(int det_ID) {
	char root_file[200];

	sprintf (root_file, "/path/to/file_%d", det_ID);  //Filename and path

	TFile *file =TFile::Open(root_file);  
	TH2 *His = (TH2*)file -> Get(Form("gm_%d", det_ID -1));    //Extract the 2D histogram
	return His;

However, for a large number of files, this is causing memory issues…“too many files open at the moment”, however when I put the file->Close(); I get a segmentation fault.
Is it possible to close the file and still return the His?

Thanks a lot

Hi Utkarsh,

The issue here is that histograms are owned by the file from which they were read. You can detach them from the file invoking the method SetDirectory(nullptr). See the doc here for more info.

I hope this unblocks you.


Thank You @Danilo, for the lucid expalnation.