Segmentation violation on closing TFile

Hello,
I am having trouble with a very simple matter. The following code attempts to create a directory and save a histogram in it AND not use new to create the histogram. Unfortunately it gives a segfault. Why is that?

int main ()
{
  TFile *f = new TFile("test.root","RECREATE");
  f->mkdir( "0" )->cd();
  TH1F b =  TH1F("bb", "bb", 1,0,1);
  f->Close();
  return 0;
}

Surely with

TH1F *b =  new TH1F("bb", "bb", 1,0,1);

it works, but why? Can I still somehow fix the original example without using new?

I am using root 6.06 and g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44)

Hi @mrTuna, welcome on the forum!

You facing histogram ownership problem.
Just look in TH1 documentation.
Before creating histogram you can call:

TH1::AddDirectory(kFALSE);

Then your example will work.

Regards,
Sergey

1 Like

Hi @linev,
thank you for the answer. That was helpful.

For future reference I found this useful also: ObjectOwnership

1 Like