TFile and TTree, errors

_ROOT Version: 5.34
_Platform: Ubuntu 18

In my code I open a TFile and read the TTree and do calculations with it. I store the calculations in a list, and at the end of my code I want to store these in another TTree, and write it to another File. I have a subclass which at the start-up does this:

myTree = new TTree(…); // myTree is a member of the subclass

and at the end of the program, another method is called which does:

TFile* myRootFile = new TFile( "TEST.root", "RECREATE");
mytree->Write();

This gives the error (during filling):

Error in TTree::Fill: Failed filling branch:GmSDTTree.hit_Energy, nbytes=-1, entry=11967
This error is symptomatic of a Tree created as a memory-resident Tree
Instead of doing:
TTree *T = new TTree(…)
TFile *f = new TFile(…)
you should do:
TFile *f = new TFile(…)
TTree *T = new TTree(…)

So, then I changed the code. Now at start-up I do:

myRootFile = new TFile( "TEST.root", "RECREATE");  // myRootFile is a class member 
mytree = new TTree("GmSDTTree", "");    // myTree is a member of the subclass

And at the end of the code:

mytree->Write();

Now, the error is:

Error in TROOT::WriteTObject: The current directory (root) is not associated with a file. The object (GmSDTTree) has not been written.

So, then, at the end of the code, I do:

myRootFile->cd();
mytree->Write();

Now I get the error:

*** Break *** segmentation violation

(The pointer is still valid, I didn’t delete it)
How do I fix this?

Try:

if (myRootFile && mytree) { // just a precaution
  myRootFile->cd();
  mytree->Write();
  delete myRootFile; // automatically deletes "mytree", too
  myRootFile = 0;
  mytree = 0;
}

THank you. Indeed you’re right. The crash actuallt was caused by the deletion of Tree without deleting TFile. Only deleting myRootFile (and not mytree) solved the problem. Thank you for your help.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.