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

**URL:** <https://root-forum.cern.ch/t/memory-issues-while-loading-2d-histograms-by-opening-multiple-root-files/58533>\
**Category:** Newbie\
**Created:** [March 14, 2024, 6:09am UTC](https://root-forum.cern.ch/t/memory-issues-while-loading-2d-histograms-by-opening-multiple-root-files/58533 "2024-03-14T06:09:18Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![utkarsh-2000](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/u/e47774/32.png) [@utkarsh-2000](https://root-forum.cern.ch/u/utkarsh-2000)\
**Post date:** [March 14, 2024, 6:09am UTC](https://root-forum.cern.ch/t/memory-issues-while-loading-2d-histograms-by-opening-multiple-root-files/58533/1 "2024-03-14T06:09:18Z")

</div>

Hi all,

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

```auto
TH2* Load2DHist(int det_ID) {
	//File
	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
	
	//file->Close();  
	
	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

---

<div class="post-metadata">

**Author:** ![Danilo](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/danilo/32/34528_2.png) [@Danilo](https://root-forum.cern.ch/u/Danilo)\
**Post date:** [March 14, 2024, 8:05am UTC](https://root-forum.cern.ch/t/memory-issues-while-loading-2d-histograms-by-opening-multiple-root-files/58533/2 "2024-03-14T08:05:42Z")

</div>

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](https://root.cern.ch/doc/master/classTH1.html#a0367fe04ae8709fd4b82795d0a5462c3) for more info.

I hope this unblocks you.

Best,  
D

---

<div class="post-metadata">

**Author:** ![utkarsh-2000](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/u/e47774/32.png) [@utkarsh-2000](https://root-forum.cern.ch/u/utkarsh-2000)\
**Post date:** [March 14, 2024, 3:00pm UTC](https://root-forum.cern.ch/t/memory-issues-while-loading-2d-histograms-by-opening-multiple-root-files/58533/3 "2024-03-14T15:00:45Z")

</div>

Thank You @Danilo, for the lucid expalnation.
