Question concerning ownership + garbagecollection

Dear Rooters,

I observed something that i do not understand:
When I have executed the following lines in cint and
want to exit it gives me a segmentation fault

TH1D h;
TFile f(“test.root”, “recreate” );
h.SetName(“test”);
h.SetDirectory( &f );
f.Write();
f.ls();
f.Close();

Am I not supposed to be able to change the directory
of a Histogram after creating it ?

The histogram gets delete at the f.Close(), as it should be,
but after that it seems that some garbagecollection wants
to delete it again.

thanks for any replies
Michael

Just move the statement “TH!f h” after the craetion of TFile.
Histograms are created in teh current directory.

Rene

[quote=“brun”]Just move the statement “TH!f h” after the craetion of TFile.
Histograms are created in teh current directory.

Rene[/quote]

Hi Rene,
thank you for the fast answer.
I used to do it as you said, the code I sent
was only meant as an example.
Nevertheless: am I right that it should work
in principle ?

What I really would like to do is the following

// does not crash, but histograms do not
// get written to the file
// or with the SetDirectory statements
// crashes at exit

TFile *f = new TFile(“test.root”, “recreate” );
f->cd();
TH1D *h;

// with or without the constructor parameters
// seems anyway that cint ignores them
// but i tried also with a compiler
h = new TH1D[2](“t”, “t”, 1, 0, 1 );
h[0]->SetName(“t1”);
h[1]->SetName(“t2”);

f->ls();
// they were not created in the
// current directory, although I
// expected it

h[0]->SetDirectory( &f );
h[1]->SetDirectory( &f );
f->ls();
//now they are in the current directory

f->Write();
f->Close();

sorry for using your time
Michael

What you do is illegal C++. Do something like:

TFile *f = new TFile(“test.root”, “recreate” );
TH1D *h[2];
h[0] = new TH1D(“t1”,“t1”,1,0,1)
h[1] = new TH1D(“t2”,“t2”,1,0,1)
f->Write()

Rene

Hi Rene,
thanks for your really fast help.
It works fine as you said.
I still did not quite understand why
the other thing was wrong :unamused:
but since it works …

thanks again + best wishes
Michael

Michael,

In your code, you had several invalid statements;

====
TH1D *h;
h = new TH1D[2](“t”, “t”, 1, 0, 1 );

and
h[0]->SetDirectory( &f );
must be:
h[0]->SetDirectory(f);

Rene