Segmentation violation when using TH1D and ofstream

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 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

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:

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)