# Segmentation violation when using TH1D and ofstream

**URL:** <https://root-forum.cern.ch/t/segmentation-violation-when-using-th1d-and-ofstream/55664>\
**Category:** ROOT\
**Tags:** hist, root\
**Created:** [July 13, 2023, 4:05pm UTC](https://root-forum.cern.ch/t/segmentation-violation-when-using-th1d-and-ofstream/55664 "2023-07-13T16:05:31Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![eguiraud](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/eguiraud/32/32217_2.png) [@eguiraud](https://root-forum.cern.ch/u/eguiraud)\
**Post date:** [July 13, 2023, 4:49pm UTC](https://root-forum.cern.ch/t/segmentation-violation-when-using-th1d-and-ofstream/55664/2 "2023-07-13T16:49:33Z")

</div>

Hi @KevinH ,

I think the problem is that the `TFile` takes ownership of the trees and histograms that are created after it. So `file->Close` deletes them. So you don’t need to `delete` them explicitly.

You can verify this is what is happening by [running the reproducer under valgrind](https://root-forum.cern.ch/t/valgrind-and-root/28506) after compiling the repro with debug symbols (and ideally also using a ROOT build that has debug symbols).

Cheers,  
Enrico

P.S.  
more details about TFile ownership at [Object ownership - ROOT](https://root.cern/manual/object_ownership/#ownership-by-current-directory-gdirectory)

P.P.S.  
however you do need to call `delete file`, otherwise you are leaking a (closed) TFile object.

P.P.P.S.

you can make all the memory management automatic by using a unique\_ptr for the TFile and allocate the histogram on the stack:

```cpp
std::unique_ptr<TFile> file(TFile::Open(fileNames[i]));
/* ... */
// tree is owned by file
TTree* tree = file->Get<TTree>("evt");
/* ... */
TH1D hist("hist", "depositenergy", 200, 0, 3);
/* ... */
// no need to call file->Close (it's called by its destructor)
// no need to `delete tree` (it's owned by the file which will take care of destructing it)
// no need to `delete hist` (it's stack-allocated)

```

---

_[View the full topic](https://root-forum.cern.ch/t/segmentation-violation-when-using-th1d-and-ofstream/55664)._
