Saving a TTree in a file and cleaning memory

Hi,

I want to save a TTree in a TFile. I do that in a loop, changing the file name at each iteration. My code looks like:

for(int i = 0; i<N; i++){
    TFile *fout = new TFile("myfile.root", "recreate");
    fout->cd();
    TTree *T = new TTree("mytree", "mytree");

    [Here I fill my TTree]

    fout->Write();
    fout->Close();
}

First of all, does the code looks correct?

My question is about cleaning up the memory. Do I need to delete the TTree before closing the file? Or it is automatically done when closing the file?

Thank you for your help!

As you recreate the TFile at each iteration you will end up with the last TTree in the Last TFile

Sorry, my code was not clear as I was trying to simplify it for the forum. The file name actually changes at every iteration: “myfile_0.root”, “myfile_1.root”, “myfile_2.root”…

To avoid memory leaks, do I have to “delete T;” at every iteration of the loop? Or is it automatically done when I close the file.

Yes you can delete before create the new one.

Thank you Couet. My question is rather can I close the file without deleting the TTree? Would that be OK in terms of RAM?

My code is structured in such a way that it is difficult to delete the TTree, so It would be great if the memory is freed when I close the file. It looks like it is because, after closing the file, the TTree can no longer be used because of ownership.

I would say yes … just try …

Not quite. The end is:

    fout->Close();

which close out the file and will delete the TTree object but will NOT delete the TFile object: so you have a memory leak. Rather than calling Close your delete the TFile (which will indirectly call Close:

    delete fout;

Do I need to delete the TTree before closing the file?

You can but don’t have to (the Close will delete it). The only requirement is that fout->Write() must be called before you delete the tree.

My question is rather can I close the file without deleting the TTree? Would that be OK in terms of RAM?

It is unlikely to be okay in term of RAM (unless you have small trees).
More importantly keeping a TTree object around without its back TFile requires to first load all the data back into memory.

My code is structured in such a way that it is difficult to delete the TTree,

Humm then I misunderstood you in my previous point. Rather than wanting to keep the TTree in memory, you are asking about not calling explicitly delete tree; … and that part is fine since the TTree is co-owned by you and the TFile and TFile::Close (and thus delete fout; will delete the TTree).

Thank you all for your answers. I think I have what I need!

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